Lab 1
Lab 1
Sr Remarks
PROGRAMS
No.
1. Program in Java to implement Print Prime Number Upto 100
Output:-
2
2. Program in Java to implement finding whether a number is Armstrong or not.
Solution:-
public class Armstrong {
public static void main(String [] arg){
int num=153;
int n=num;
int sum=0;
int noOfDigits=0;
while(n>0){
n=n/10;
noOfDigits++;
}
n=num;
while(n>0){
int r=n%10;
n=n/10;
sum=sum+(int)Math.pow(r, noOfDigits);
}
if(sum==num){
System.out.println(num+" is an Armstrong number");
}else{
System.out.println(num+" is not an Armstrong number");
}
}
}
Output:-
3
3. Program in Java to implement array reading and writing on/from console.
Solution:-
import java.util.Scanner;
public class ArrayReadWrite {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Array elements:");
for (int i = 0; i < size; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
scanner.close();
}
}
Output:-
4
4. Program in Java to implement selection sort using functions.
Solution:-
public class Sort{
public static void main(String []arg){
int [] arr={54,3,34,45,33,456,232,65,90};
selectionSort(arr);
for(int i:arr){
System.out.print(i+" ");
}
}
public static void selectionSort(int [] arr){
System.out.println("Using selection sort:\n");
for(int i=0;i<arr.length-1;i++){
int minIndex=i;
for(int j=i+1;j<arr.length;j++){
if(arr[j]<arr[minIndex]){
minIndex=j;
}
}
if(minIndex!=i){
int temp=arr[i];
arr[i]=arr[minIndex];
arr[minIndex]=temp;
}
}
}
}
Output:-
5
5. Program in Java to implement Bubble Sort using Functions.
Solution:-
public class Sort{
public static void main(String []arg){
int [] arr={54,3,34,45,33,456,232,65,90};
bubbleSort(arr);
for(int i:arr){
System.out.print(i+" ");
}
}
public static void bubbleSort(int [] arr){
System.out.println("Using bubble sort:\n");
for(int i=0;i<arr.length-1;i++){
for(int j=0;j<arr.length-i-1;j++){
if(arr[j]>arr[j+1]){
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
}
Output:-
6
6. Program in Java to implement Insertion sort using functions.
Solution:-
public class Sort{
public static void main(String []arg){
int [] arr={54,3,34,45,33,456,232,65,90};
insertionSort(arr);
for(int i:arr){
System.out.print(i+" ");
}
}
public static void insertionSort(int [] arr){
System.out.println("using insertion sort:");
int temp;
for(int i=1;i<arr.length;i++){
temp=arr[i];
int j=i-1;
while(j>=0&&arr[j]>temp){
if(temp<arr[j]){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=temp;
}
}
}
}
Output:-
7
7. Program in Java to implement Matching a Particular Substring in a String without using
inbuilt matching function(s).
Solution:-
public class SubString {
public static void main(String []arg){
String str ="Welcome to the world of programming";
if(isSubString(str, "world")){
System.out.println("Substring found..");
}
}
static boolean isSubString(String string,String subString){
char stringarr[]=string.toCharArray();
char substringarr[]=subString.toCharArray();
for(int i=0;i<stringarr.length;i++){
if(stringarr[i]==substringarr[0]){
for(int j=0;j<substringarr.length;j++){
if(i+j<stringarr.length && stringarr[i+j]==substringarr[j]){
if(j==(substringarr.length-1))return true;
}else{
break;
}
}
}
}
return false;
}
}
Output:-
8
8. Program in Java to implement Garbage Collection Usage in Java.
Solution:-
class Abc{
int a;
int b;
char c;
Abc(int a,int b, char c){
this.a=a;
this.b=b;
this.c=c;
}
public void show(){
System.out.println(a+" "+c+" "+b);
}
public void finalize(){
System.out.println("The object is collected by Garbage collector");
}
}
public class GarbageCollection {
public static void main(String []arg){
Abc A=new Abc(4,2,'+');
Abc B=new Abc(6,2,'*');
A.show();
B.show();
A=null;
System.gc();
}
}
Output:-
9
9. Program in Java to implement array of objects and create a student record with details of
name, address, contact number and email ID
Solution:-
//Student class
public class Student {
public String name;
public String address;
public long phoneNo;
public String email;
public Student(String name,String address,long phoneNo,String email){
this.address=address;
this.email=email;
this.name=name;
this.phoneNo=phoneNo;
}
public String toString(){
return "\nName : "+name+" \nAddress : "+address+" \nPhone No : "+phoneNo+" \nEmail : "+email;
}
}
//main class
public class ObjectArray {
public static void main(String []arg){
Student [] students=new Student[3];
students[0]=new Student("Aakash","Sampla",9575674536l,"[email protected]");
students[1]=new Student("Vishal","Jhajjar",5423453245l,"[email protected]");
students[2]=new Student("Rahul","Rohtak",9865325689l,"[email protected]");
System.out.println(students[0]);
System.out.println(students[2]);
}
}
Output:-
10
10. Program in Java to implement Single & Multi-level inheritance.
Solution:-
//Calculator class base class
package inheritance;
public class Calculator {
public int sum(int a, int b){
return a+b;
}
public int sub(int a, int b){
return a-b;
}
public int multiply(int a, int b){
return a*b;
}
public int divide(int a, int b){
return a/b;
}
}
//phone class derived class for calculator and base class for smartphone
package inheritance;
public class Phone extends Calculator{
public void call(long p){
System.out.println("Calling...\n"+p);
}
public void sms(long p,String msg){
System.out.println("Message sent successfully.\nReceiver : "+p+"\nMessage : "+msg);
}
public static void main(String []arg){
Phone phone =new Phone();
System.out.println("Sum of 3 , 4 is :"+phone.sum(3,4));
phone.sms(9588385856l, "Hello");;
}
}
//smartphone class derived class
package inheritance;
public class Smartphone extends Phone {
11
public static void main(String []main){
Smartphone smartPhone = new Smartphone();
smartPhone.music();
smartPhone.call(9588385856l);
System.out.println(smartPhone.divide(40, 4));
}
Output:-
12
11. Program in Java to implement Abstract Class Usage.
Solution:-
//abstract class car
package abstractclass;
public abstract class Car {
abstract void accelerate();
abstract void deaccelerate();
}
//main class tata that inherit car
package abstractclass;
public class Tata extends Car{
void accelerate(){
System.out.println("Accelerating..");
}
void deaccelerate(){
System.out.println("Deaccelerating..");
}
public static void main(String[] args){
Car tata = new Tata();
tata.accelerate();
tata.deaccelerate();
}
}
Output:-
13
12. Program in Java to implement Interface Usage to implement multiple inheritance.
Solution:-
//interface color
package interfaces;
public interface Color {
void fillColor(String s);
}
//interface shape
package interfaces;
interface Shape{
float area();
float parameter();
}
//main class rectangle that implements shape and color
package interfaces;
public class Rectangle implements Shape,Color {
float length;
float bredth;
Rectangle(float l,float b){
length=l;
bredth=b;
}
public float area(){
return length*bredth;
}
public float parameter(){
return 2*(length+bredth);
}
public void fillColor(String s){
System.out.println("Rectangle is filled with "+s+"color.");
}
System.out.println("Area : "+r1.area());
System.out.println("Parameter : "+r1.parameter());
r1.fillColor("Orange");
}
}
14
Output:-
13. Program in Java to implement Packages usage to use one function of a class in another.
Solution:-
//package 1 MyClass1
package package1;
public class MyClass1 {
public static void myMethod() {
System.out.println("This is a method from Package1");
}
}
//package2 MyClass2
package package2;
import package1.MyClass1;
Output:-
15
14. Program in Java to implement I/O and file handling
Solution:-
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class FileHandeling {
private String name;
FileHandeling(String fileName){
name=fileName;
}
public boolean createFile(){
File fo =new File(name);
try{
fo.createNewFile();
return true;
}catch(Exception e){
return false;
}
}
public void write(String s){
try {
FileWriter fw =new FileWriter(name);
fw.write(s);
fw.close();
} catch (Exception e) {}
}
public void readFile(){
try{
File fo = new File(name);
Scanner sc=new Scanner(fo);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
sc.close();
}catch(Exception e){ }
}
public static void main(String [] args){
FileHandeling fh=new FileHandeling("data.txt");
fh.write("Hello world!");
fh.readFile();
}}
16
Output:-
17
Output:-
//appletsum class
import java.awt.event.*;
import java.applet.Applet;
import java.awt.*;
18
TextField t3=new TextField(10);
Label l1=new Label("First Number");
Label l2=new Label("Second Number");
Label l3=new Label("Sum");
Button b=new Button("Add");
Output:-
19
17. Program in Java to implement Multiple Threads.
Solution:-
class SimpleThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getId() + " - Count: " + i);
}
}
}
public class Thread1 {
public static void main(String args[]) {
SimpleThread thread1 = new SimpleThread();
SimpleThread thread2 = new SimpleThread();
thread1.start();
thread2.start();
}
}
Output:-
20
18. Program in Java to implement Event Handlers
Solution:-
import java.awt.*;
import java.awt.event.*;
public class EventHandelingEg extends Frame implements ActionListener {
Button b;
int x,y,c=0;
void changePosition(){
x= (int) (100+Math.random()*400);
y=(int) (100+Math.random()*400);
b.setBounds(x,y,80,30);
c++;
}
public EventHandelingEg(){
setSize(600,600);
setVisible(true);
setLayout(null);
b=new Button("Close");
changePosition();
add(b);
b.setBackground(Color.red);
b.addActionListener(this);
b.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
if(c<21){
changePosition();
}else{
b.setBackground(Color.GREEN);
}
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
21
public static void main(String[] args) {
new EventHandelingEg();
}
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
}
Output:-
22
19. Program in Java to implement Mini Calculator
Solution:-
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
n0=new Button("0");
n0.setFont(f);
n0.addActionListener(this);
n1=new Button("1");
n1.setFont(f);
n1.addActionListener(this);
n2=new Button("2");
n2.setFont(f);
n2.addActionListener(this);
23
n3=new Button("3");
n3.setFont(f);
n3.addActionListener(this);
n4=new Button("4");
n4.setFont(f);
n4.addActionListener(this);
n5=new Button("5");
n5.setFont(f);
n5.addActionListener(this);
n6=new Button("6");
n6.setFont(f);
n6.addActionListener(this);
n7=new Button("7");
n7.setFont(f);
n7.addActionListener(this);
n8=new Button("8");
n8.setFont(f);
n8.addActionListener(this);
n9=new Button("9");
n9.setFont(f);
n9.addActionListener(this);
addBtn=new Button("+");
addBtn.setFont(f);
addBtn.addActionListener(this);
subBtn=new Button("-");
subBtn.setFont(f);
subBtn.addActionListener(this);
mulBtn=new Button("*");
mulBtn.setFont(f);
mulBtn.addActionListener(this);
divBtn=new Button("/");
divBtn.setFont(f);
divBtn.addActionListener(this);
eqlBtn=new Button("=");
eqlBtn.setFont(f);
eqlBtn.addActionListener(this);
crlBtn=new Button("Clr");
crlBtn.setFont(f);
crlBtn.addActionListener(this);
delBtn=new Button("Del");
delBtn.setFont(f);
delBtn.addActionListener(this);
24
dotBtn=new Button(".");
dotBtn.setFont(f);
dotBtn.addActionListener(this);
panel.add(n1);
panel.add(n2);
panel.add(n3);
panel.add(addBtn);
panel.add(n4);
panel.add(n5);
panel.add(n6);
panel.add(subBtn);
panel.add(n7);
panel.add(n8);
panel.add(n9);
panel.add(mulBtn);
panel.add(dotBtn);
panel.add(n0);
panel.add(eqlBtn);
panel.add(divBtn);
panel.add(crlBtn);
panel.add(delBtn);
tf=new TextField(17);
tf.setEditable(false);
tf.setFont(f);
tf.setBounds(50,55,300,40);
tf.setBackground(Color.blue);
frame.add(tf);
frame.add(panel);
frame.setLayout(null);
frame.setVisible(true);
if(e.getSource()==n0){
tf.setText(tf.getText()+0);
}else if(e.getSource()==n1){
tf.setText(tf.getText()+1);
}else if(e.getSource()==n2){
tf.setText(tf.getText()+2);
}else if(e.getSource()==n2){
tf.setText(tf.getText()+2);
}else if(e.getSource()==n3){
tf.setText(tf.getText()+3);
}else if(e.getSource()==n4){
tf.setText(tf.getText()+4);
}else if(e.getSource()==n5){
tf.setText(tf.getText()+5);
}else if(e.getSource()==n6){
tf.setText(tf.getText()+6);
}else if(e.getSource()==n7){
tf.setText(tf.getText()+7);
}else if(e.getSource()==n8){
tf.setText(tf.getText()+8);
}else if(e.getSource()==n9){
tf.setText(tf.getText()+9);
}else if(e.getSource()==addBtn){
dotPresent=false;
String s=tf.getText();
if(s.endsWith("-")||s.endsWith("*")||s.endsWith("/")){
tf.setText(tf.getText()+"+");
}else{
tf.setText(calculate(tf.getText())+"+");
}
}else if(e.getSource()==subBtn){
dotPresent=false;
String s=tf.getText();
if(s.endsWith("*")||s.endsWith("/")){
tf.setText(tf.getText()+"-");
}else{
tf.setText(calculate(tf.getText())+"-");
26
}
}else if(e.getSource()==mulBtn){
dotPresent=false;
tf.setText(calculate(tf.getText())+"*");
}else if(e.getSource()==divBtn){
dotPresent=false;
tf.setText(calculate(tf.getText())+"/");
}else if(e.getSource()==eqlBtn){
dotPresent=false;
tf.setText(calculate(tf.getText()));
}else if(e.getSource()==crlBtn){
dotPresent=false;
tf.setText("");
} else if (e.getSource()==delBtn) {
String s=tf.getText();
if(s.endsWith(".")){
dotPresent=false;
}
if(!s.isEmpty()){
tf.setText((String)s.subSequence(0,s.length()-1));
}
} else if (e.getSource()==dotBtn) {
if(!dotPresent){
tf.setText(tf.getText()+".");
dotPresent=true;
}
}
}
public String calculate(String s){
char operator=0;
char[] eq=s.toCharArray();
int oIndex = 0;
if(eq.length>1){
for(int i=1;i<eq.length;i++){
if(eq[i]=='+'){
operator='+';
oIndex=i;
break;
}else if(eq[i]=='-'){
operator='-';
oIndex=i;
27
break;
}else if(eq[i]=='*'){
operator='*';
oIndex=i;
break;
}else if(eq[i]=='/'){
operator='/';
oIndex=i;
break;
}
}
}else{
if(eq.length==1){
if(eq[0]=='+'||eq[0]=='-'||eq[0]=='*'||eq[0]=='/'){
return "";
}
return s;
}else{
return s;
}
}
if(oIndex==0){
return s;
}else if(oIndex==s.length()-1){
return s.substring(0,s.length()-1);
}
num1=Double.parseDouble(s.substring(0,oIndex));
num2=Double.parseDouble( s.substring(oIndex+1));
try{
switch (operator){
case '+':
result=num1+num2;
break;
case '-':
result=num1-num2;
break;
case '*':
result=num1*num2;
break;
case '/':
result=num1/num2;
28
}
}catch (Exception e){
return "ERROR!!!";
}
return String.valueOf(result);
}
}
Output:-
29
20. Program in Java to define two complex numbers and do the addition and multiplication and
print the results.
Solution:-
import java.util.Scanner;
public class ComplexNumber {
public static void addComplexNumber(Complex a,Complex b){
System.out.println("Sum of "+a.realPart+"+"+a.imaginaryPart+"i"+ " and "+
b.realPart+"+"+b.imaginaryPart+"i"+" is : "+(a.realPart+b.realPart)+"+"+(a.imaginaryPart+
b.imaginaryPart)+"i");
}
public static void mulComplexNumber(Complex a,Complex b){
System.out.println("Multiplication of "+a.realPart+"+"+a.imaginaryPart+"i"+ " and "+
b.realPart+"+"+b.imaginaryPart+"i"+" is : "+((a.realPart*b.realPart)-
(a.imaginaryPart*b.imaginaryPart))+
"+"+((a.realPart*b.imaginaryPart)+(a.imaginaryPart*b.realPart))+"i");
}
public static void main(String [] arg){
Complex c1=new Complex(),c2=new Complex();
Scanner sc=new Scanner(System.in);
System.out.println("Enter first complex number:\nReal Part:");
c1.realPart=sc.nextInt();
System.out.println("Imaginary Part:");
c1.imaginaryPart=sc.nextInt();
System.out.println("Enter second complex number:\nReal Part:");
c2.realPart=sc.nextInt();
System.out.println("Imaginary Part:");
c2.imaginaryPart=sc.nextInt();
addComplexNumber(c1, c2);
mulComplexNumber(c1,c2);
sc.close();
}
}
class Complex{
public int realPart;
public int imaginaryPart;
Complex(){
}
Complex(int real,int imaginary){
realPart=real;
imaginaryPart=imaginary;
30
}
}
Output:-
31
Computer Graphics Programs
INDEX
Sr PROGRAMS Remarks
No.
21. Program in C to implement DDA line drawing algorithm
25. Program in C to implement a moving object like car / fan / moving man.
32
21. Program in C to implement DDA line drawing algorithm.
Solution:-
#include <graphics.h>
#include <stdio.h>
#include <math.h>
void DDA(int x1, int y1, int x2, int y2) {
int dx = x2 - x1;
int dy = y2 - y1;
int steps, k;
float xIncrement, yIncrement, x = x1, y = y1;
if (abs(dx) > abs(dy))
steps = abs(dx);
else
steps = abs(dy);
xIncrement = dx / (float)steps;
yIncrement = dy / (float)steps;
for (k = 0; k <= steps; k++) {
putpixel((int)(x + 0.5), (int)(y + 0.5), WHITE);
x += xIncrement; // Increment x
y += yIncrement; // Increment y
}
}
int main() {
int gd = DETECT, gm;
int x1, y1, x2, y2;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
printf("Enter the coordinates of the first point (x1, y1): ");
scanf("%d %d", &x1, &y1);
printf("Enter the coordinates of the second point (x2, y2): ");
scanf("%d %d", &x2, &y2);
DDA(x1, y1, x2, y2);
getch();
closegraph();
return 0;
}
33
Otuput:-
if (p < 0) {
p = p + 2 * dy;
} else {
p = p + 2 * dy - 2 * dx;
y++;
34
}
x++;
}
}
int main() {
int gd = DETECT, gm;
int x1, y1, x2, y2;
getch();
closegraph();
return 0;
}
Output:-
35
23. Program in C to implement Circle drawing using polynomial approach.
Solution:-
#include <graphics.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
void drawCircle(int xc, int yc, int r) {
int x, y;
for (x = xc - r; x <= xc + r; x++) {
y = yc + sqrt(r * r - (x - xc) * (x - xc));
putpixel(x, y, WHITE);
y = yc - sqrt(r * r - (x - xc) * (x - xc));
putpixel(x, y, WHITE);
}
}
int main() {
int gd = DETECT, gm;
int xc, yc, r;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
printf("Enter center of circle (xc, yc): ");
scanf("%d %d", &xc, &yc);
printf("Enter radius of circle: ");
scanf("%d", &r);
drawCircle(xc, yc, r);
getch();
closegraph();
return 0;
}
Output:-
36
24. Program in C to implement Circle drawing using Bresenham’s approach.
Solution:-
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
void plotCirclePoints(int xc, int yc, int x, int y) {
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);
}
while (y >= x) {
x++;
if (d > 0) {
y--;
d = d + 4 * (x - y) + 10;
} else {
d = d + 4 * x + 6;
}
int main() {
int gd = DETECT, gm;
int xc, yc, r;
37
printf("Enter the center of circle (xc, yc): ");
scanf("%d %d", &xc, &yc);
printf("Enter the radius of the circle: ");
scanf("%d", &r);
getch();
closegraph();
return 0;
}
Output:-
38
25. Program in C to implement a moving object like car / fan / moving man.
Solution:-
#include <graphics.h>
#include <conio.h>
#include <dos.h>
int main() {
int gd = DETECT, gm;
int x = 0, y = 300;
while (!kbhit()) {
setcolor(WHITE);
drawCar(x, y);
delay(50);
eraseCar(x, y);
x += 10;
if (x > getmaxx()) {
x = 0;
}
39
}
getch();
closegraph();
return 0;
}
Output:-
40
26. Program in C to implement color filling in a closed object.
Solution:-
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
int main() {
int gd = DETECT, gm;
int left, top, right, bottom, fillColor, borderColor;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
left = 150;
top = 100;
right = 300;
bottom = 200;
borderColor = WHITE;
fillColor = RED;
setcolor(borderColor);
rectangle(left, top, right, bottom);
floodfill((left + right) / 2, (top + bottom) / 2, borderColor);
getch();
closegraph();
return 0;
}
Output:-
41
27. Program in C to implement bouncing ball.
Solution:-
#include <graphics.h>
#include <conio.h>
#include <dos.h>
int main() {
int gd = DETECT, gm;
int x = 200, y = 50;
int radius = 20;
int dy = 5;
while (!kbhit()) {
cleardevice();
y += dy;
if (y > getmaxy() - radius || y < radius) {
dy = -dy;
}
setcolor(WHITE);
fillellipse(x, y, radius, radius);
delay(30);
}
getch();
closegraph();
return 0;
}
42
Output:-
43
28. Program in C to implement point clipping/line clipping method.
Solution:-
#include <graphics.h>
#include <conio.h>
#include <stdio.h>
#define LEFT 1
#define RIGHT 2
#define BOTTOM 4
#define TOP 8
int xmin = 100, ymin = 100, xmax = 300, ymax = 300;
int computeCode(int x, int y) {
int code = 0;
if (x < xmin) code |= LEFT;
if (x > xmax) code |= RIGHT;
if (y < ymin) code |= BOTTOM;
if (y > ymax) code |= TOP;
return code;
}
void cohenSutherlandClip(int x1, int y1, int x2, int y2) {
int code1 = computeCode(x1, y1);
int code2 = computeCode(x2, y2);
int accept = 0;
while (1) {
if ((code1 == 0) && (code2 == 0)) {
accept = 1;
break;
} else if (code1 & code2) {
break;
} else {
int code_out;
int x, y;
if (code1 != 0)
code_out = code1;
else
code_out = code2;
44
y = ymax;
} else if (code_out & BOTTOM) {
x = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1);
y = ymin;
} else if (code_out & RIGHT) {
y = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1);
x = xmax;
} else if (code_out & LEFT) {
y = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1);
x = xmin;
}
if (code_out == code1) {
x1 = x;
y1 = y;
code1 = computeCode(x1, y1);
} else {
x2 = x;
y2 = y;
code2 = computeCode(x2, y2);
}
}
}
if (accept) {
setcolor(WHITE);
line(x1, y1, x2, y2);
}
}
int main() {
int gd = DETECT, gm;
int x1, y1, x2, y2;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
rectangle(xmin, ymin, xmax, ymax);
printf("Enter the coordinates of the line (x1, y1, x2, y2): ");
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
setcolor(YELLOW);
line(x1, y1, x2, y2);
getch();
cleardevice();
rectangle(xmin, ymin, xmax, ymax);
45
cohenSutherlandClip(x1, y1, x2, y2);
getch();
closegraph();
return 0;
}
Output:-
46
29. Program in C to implement analog clock.
Solution:-
#include <graphics.h>
#include <conio.h>
#include <math.h>
47
line(xc, yc, x, y);
}
int main() {
48
int gd = DETECT, gm;
int xc = 200, yc = 200; // Center of the clock
int radius = 100; // Radius of the clock face
getch();
closegraph();
return 0;
}
Output:-
49
30. Program in C to implement a three dimensional object / smiley.
Solution:-
#include <graphics.h>
#include <conio.h>
int main(){
int graphicdriver=DETECT,graphicmode;
initgraph(&graphicdriver,&graphicmode,"c:\\turboc3\\bgi");
outtextxy(10, 10 + 10, "Program to draw a smiley face in C graphics");
setcolor(YELLOW);
circle(300, 100, 40);
setfillstyle(SOLID_FILL, YELLOW);
floodfill(300, 100, YELLOW);
setcolor(BLACK);
setfillstyle(SOLID_FILL, BLACK);
creating face.
fillellipse(310, 85, 2, 6);
fillellipse(290, 85, 2, 6);
ellipse(300, 100, 205, 335, 20, 9);
ellipse(300, 100, 205, 335, 20, 10);
ellipse(300, 100, 205, 335, 20, 11);
getch();
return 0;
}
Output:-
50
COMPILER DESIGN PROGRAMS
INDEX
Sr PROGRAMS Remarks
No.
WAP to find length of string, concatenation of two strings without using inbuilt
31.
function
32. WAP to print a Symbol Table
51
31. WAP to find length of string, concatenation of two strings without using inbuilt function
Solution:-
public class StringConcationation{
static String concat(String s1,String s2){
int l=s1.length()+s2.length();
char[] r=new char[l];
int i=0;
for(char c:s1.toCharArray()){
r[i]=c;
i++;
}
for(char c:s2.toCharArray()){
r[i]=c;
i++;
}
return new String(r);
}
public static void main(String[] args) {
String s1="Hello ",s2="World!";
System.out.println(concat(s1,s2));
}
}
Output:-
52
32. WAP to print a Symbol Table.
Solution:-
package compilerdesign;
import java.util.HashMap;
import java.util.Map;
class SymbolTable {
private Map<String, Symbol> symbolTable;
public SymbolTable() {
symbolTable = new HashMap<>();
}
public void insert(String name, String type, String scope) {
Symbol symbol = new Symbol(type, scope);
symbolTable.put(name, symbol);
}
public Symbol lookup(String name) {
return symbolTable.get(name);
}
public void printSymbolTable() {
for (Map.Entry<String, Symbol> entry : symbolTable.entrySet()) {
System.out.println("Name: " + entry.getKey() + ", Type: " + entry.getValue().type + ", Scope: " +
entry.getValue().scope);
}
}
static class Symbol {
String type;
String scope;
public Symbol(String type, String scope) {
this.type = type;
this.scope = scope;
}
}
}
public class SymbolTable1 {
public static void main(String[] args) {
SymbolTable symbolTable = new SymbolTable();
symbolTable.insert("x", "int", "global");
symbolTable.insert("y", "float", "local");
symbolTable.insert("myFunction", "function", "global");
symbolTable.printSymbolTable();
}
}
53
Output:-
Output:-
54
34. WAP to validate an email ID/Mobile Number.
Solution:-
//Email validation
package compilerdesign;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePhoneNo{
public static void main(String [] arg){
Scanner sc = new Scanner(System.in);
System.out.println("Enter phone number : ");
String number=sc.nextLine();
Pattern pattern=Pattern.compile("^+{0,1}\\d{0,2}\s*[6-9]{1}\\d{9}$");
Matcher m=pattern.matcher(number);
boolean b=m.matches();
System.out.println(b);
sc.close();
55
}
}
Output:-
35. WAP to check number of single spaces, double spaces and multiple spaces in a given string.
Print the resultant string after replacing double/multiple spaces with single space.
Solution:-
package compilerdesign;
Output:-
57