Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views57 pages

Lab 1

The document outlines a series of Java programming exercises, each implementing various concepts such as sorting algorithms, inheritance, file handling, and exception handling. It includes code snippets and brief descriptions for each program, demonstrating practical applications of Java programming. The programs range from basic tasks like printing prime numbers to more complex implementations like event handling and applets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views57 pages

Lab 1

The document outlines a series of Java programming exercises, each implementing various concepts such as sorting algorithms, inheritance, file handling, and exception handling. It includes code snippets and brief descriptions for each program, demonstrating practical applications of Java programming. The programs range from basic tasks like printing prime numbers to more complex implementations like event handling and applets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

INDEX

Sr Remarks
PROGRAMS
No.
1. Program in Java to implement Print Prime Number Upto 100

2. Program in Java to implement finding whether a number is Armstrong or not.

3. Program in Java to implement array reading and writing on/from console.

4. Program in Java to implement selection sort using functions

5. Program in Java to implement Bubble Sort using Functions.

6. Program in Java to implement Insertion sort using functions.


Program in Java to implement Matching a Particular Substring in a String
7.
without using inbuilt matching function(s).
8. Program in Java to implement Garbage Collection Usage in Java.
Program in Java to implement array of objects and create a student record
9.
with details of name, address, contact number and email ID
10. Program in Java to implement Single & Multi-level inheritance.

11. Program in Java to implement Abstract Class Usage.


Program in Java to implement Interface Usage to implement multiple
12.
inheritance
Program in Java to implement Packages usage to use one function of a class
13.
in another.
14. Program in Java to implement I/O and file handling

15. Program in Java to implement Exceptions.

16. Program in Java to implement Applets.

17. Program in Java to implement Multiple Threads.

18. Program in Java to implement Event Handlers

19. Program in Java to implement Mini Calculator.


Program in Java to define two complex numbers and do the addition and
20.
multiplication and print the results.
1
1. Program in Java to implement Print Prime Number Upto 100.
Solution:-
class PrimeNo{
public static void main(String[] arg) {
for (int n = 0; n <= 100; n++) {
boolean isPrime = true;
if (n == 1 || n == 0) {
isPrime = false;
} else {
for (int i = 2; i <= (n / 2); i++) {
if ((n % i) == 0) {
isPrime = false;
break;
} else {
isPrime = true;
}
}
}
if (isPrime) {
System.out.print(n + ",");
}
}
}
}

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("Enter the elements of the array:");


for (int i = 0; i < size; i++) {
array[i] = scanner.nextInt();
}

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 {

public void music(){


System.out.println("Playing music.....");
}

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.");
}

public static void main(String [] arg){


Rectangle r1=new Rectangle(5f,10f);

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;

public class MyClass2 {


public static void main(String[] args) {
MyClass1.myMethod();
}
}

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:-

15. Program in Java to implement Exceptions.


Solution:-
import java.util.Scanner;
public class ExceptionHandeling{
public static void main(String [] arg){
Scanner sc =new Scanner(System.in);
System.out.println("Enter first number : ");
int a=sc.nextInt();
System.out.println("Enter second number : ");
int b=sc.nextInt();
try{
System.out.println(a/b);
}catch(ArithmeticException e){
System.out.println("Cannot divide by zero");
}finally{
sc.close();
}
}
}

17
Output:-

16. Program in Java to implement Applets.


Solution:-
//appletsum html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<applet code="appletsum.class" height="400",width="400"></applet>
</body>
</html>

//appletsum class

import java.awt.event.*;
import java.applet.Applet;
import java.awt.*;

public class appletsum extends Applet implements ActionListener


{
TextField t1=new TextField(10);
TextField t2=new TextField(10);

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");

public void init(){


add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==b){
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
t3.setText(""+(n1+n2));
}
}
}

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;

public class MiniCalculator implements ActionListener {


Frame frame;
Panel panel;
TextField tf;
Button n0,n1,n2,n3,n4,n5,n6,n7,n8,n9,addBtn,subBtn,mulBtn,divBtn,dotBtn,crlBtn,delBtn,eqlBtn;
double num1,num2,result;
boolean dotPresent=false;
Font f=new Font("Helvetica",Font.BOLD,30);
public MiniCalculator() {
num1=num2=result=0;
frame = new Frame("Calculator");
frame.setSize(420,550);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
panel=new Panel();
panel.setLayout(new GridLayout(5,4));
panel.setBounds(50,120,300,380);

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);

public static void main(String[] args) {


new MiniCalculator();
}
25
@Override
public void actionPerformed(ActionEvent e) {

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

22. Program in C to implement Bresenham’s line drawing algorithm

23. Program in C to implement Circle drawing using polynomial approach

24. Program in C to implement Circle drawing using Bresenham’s approach.

25. Program in C to implement a moving object like car / fan / moving man.

26. Program in C to implement color filling in a closed object.

27. Program in C to implement bouncing ball.

28. Program in C to implement point clipping/line clipping method.

29. Program in C to implement analog clock

30. Program in C to implement a three dimensional object / smiley

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:-

22. Program in C to implement Bresenham’s line drawing algorithm


Soultion:-
#include <graphics.h>
#include <conio.h>
#include <stdio.h>

void drawLine(int x1, int y1, int x2, int y2) {


int dx, dy, p, x, y;
dx = x2 - x1;
dy = y2 - y1;
x = x1;
y = y1;
p = 2 * dy - dx;

while (x <= x2) {


putpixel(x, y, WHITE);

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;

initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

printf("Enter x1, y1: ");


scanf("%d %d", &x1, &y1);
printf("Enter x2, y2: ");
scanf("%d %d", &x2, &y2);

drawLine(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);
}

void drawCircle(int xc, int yc, int r) {


int x = 0, y = r;
int d = 3 - 2 * r;

plotCirclePoints(xc, yc, x, y);

while (y >= x) {
x++;

if (d > 0) {
y--;
d = d + 4 * (x - y) + 10;
} else {
d = d + 4 * x + 6;
}

plotCirclePoints(xc, yc, x, y);


}
}

int main() {
int gd = DETECT, gm;
int xc, yc, r;

initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

37
printf("Enter the center of circle (xc, yc): ");
scanf("%d %d", &xc, &yc);
printf("Enter the radius of the circle: ");
scanf("%d", &r);

drawCircle(xc, yc, 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>

void drawCar(int x, int y) {


// Body of the car
rectangle(x, y, x + 100, y + 40);
rectangle(x + 15, y - 20, x + 85, y);

// Wheels of the car


circle(x + 25, y + 45, 10);
circle(x + 75, y + 45, 10);
}

void eraseCar(int x, int y) {


setcolor(BLACK);
rectangle(x, y, x + 100, y + 40);
rectangle(x + 15, y - 20, x + 85, y);
circle(x + 25, y + 45, 10);
circle(x + 75, y + 45, 10);
}

int main() {
int gd = DETECT, gm;
int x = 0, y = 300;

initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

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;

initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

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;

if (code_out & TOP) {


x = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1);

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>

// Precomputed sine and cosine values for angles in degrees


int sineTable[360];
int cosineTable[360];

// Function to initialize sine and cosine tables


void initTrigTables() {
int angle;
for (angle = 0; angle < 360; angle++) {
sineTable[angle] = sin(angle * 3.14159 / 180) * 1000; // Multiply by 1000 for integer math
cosineTable[angle] = cos(angle * 3.14159 / 180) * 1000; // Multiply by 1000 for integer math
}
}

// Function to draw the clock face


void drawClockFace(int xc, int yc, int radius) {
int i, angle, x, y;
setcolor(WHITE);
circle(xc, yc, radius); // Draw the outer circle of the clock

// Draw hour markers


for (i = 0; i < 12; i++) {
angle = i * 30; // 30 degrees between each hour marker
x = xc + (radius - 10) * cosineTable[angle] / 300; // Move closer to the edge
y = yc + (radius - 10) * sineTable[angle] / 300; // Move closer to the edge
setfillstyle(SOLID_FILL, WHITE);
fillellipse(x, y, 4, 4); // Larger dots for hour markers
}
}

// Function to draw the clock hands


void drawHand(int xc, int yc, int length, int angle, int color) {
int x, y;
x = xc + length * cosineTable[angle] / 500;
y = yc + length * sineTable[angle] / 500;
setcolor(color);

47
line(xc, yc, x, y);
}

// Function to simulate the clock movement


void drawAnalogClock(int xc, int yc, int radius) {
int hours = 10, minutes = 15, seconds = 30; // Initial time
int sec_angle, min_angle, hour_angle;

while (!kbhit()) { // Run until a key is pressed


cleardevice(); // Clear the screen for the next frame

drawClockFace(xc, yc, radius); // Draw clock face

// Calculate angles for clock hands


sec_angle = (seconds * 6) - 90; // 6 degrees per second, offset by -90 to start at the top
min_angle = (minutes * 6) + (seconds / 10) - 90; // 6 degrees per minute
hour_angle = (hours * 30) + (minutes / 2) - 90; // 30 degrees per hour

// Draw clock hands


drawHand(xc, yc, radius - 30, hour_angle, YELLOW); // Hour hand
drawHand(xc, yc, radius - 20, min_angle, GREEN); // Minute hand
drawHand(xc, yc, radius - 10, sec_angle, RED); // Second hand

delay(1000); // Delay 1 second

// Update time (manually increment)


seconds++;
if (seconds == 60) {
seconds = 0;
minutes++;
}
if (minutes == 60) {
minutes = 0;
hours++;
}
if (hours == 12) {
hours = 0;
}
}
}

int main() {
48
int gd = DETECT, gm;
int xc = 200, yc = 200; // Center of the clock
int radius = 100; // Radius of the clock face

// Initialize graphics mode


initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

// Initialize trigonometric lookup tables


initTrigTables();

// Draw the analog clock


drawAnalogClock(xc, yc, radius);

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

33. WAP to implement Pattern Matching

34. WAP to validate an email ID/Mobile Number.


WAP to check number of single spaces, double spaces and multiple spaces in a
35. given string. Print the resultant string after replacing double/multiple spaces
with single space.

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:-

33. WAP to implement Pattern Matching.


Solution:-
package compilerdesign;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternMatching {


public static void main(String[] args) {
String text = "The quick brown fox jumps over the lazy dog.";
String pattern = "\\b\\w{5}\\b"; // Matches words of length 5
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}
}
}

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;

public class ValidateEmail {


public static void main(String [] arg){
Scanner sc = new Scanner(System.in);
System.out.println("Enter E-mail : ");
String mail=sc.nextLine();
Pattern pattern=Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0_9-]+.[a-zA-Z0_9-]+$");
Matcher m=pattern.matcher(mail);
boolean b=m.matches();
if(b)
System.out.println("The email is valid.");
else
System.out.println("email is not valid");
sc.close();
}
}
//Phone validation
package compilerdesign;

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;

public class CountSpaces {


public static void main(String [] arg){
String input="This is a temperary string for this program.";
int singleSpaces=0;
int doubleSpaces=0;
int multipleSpaces=0;
for(int i=0;i<input.length();i++){
if(input.charAt(i)==' '){
int spaceCount=1;
while(i+1<input.length()&&input.charAt(i+1)==' '){
spaceCount++;
i++;
}
if(spaceCount==1){
56
singleSpaces++;
}else if(spaceCount==2){
doubleSpaces++;
}else{
multipleSpaces++;
}
}
}
System.out.println("Single spaces: "+singleSpaces);
System.out.println("Double spaces: "+doubleSpaces);
System.out.println("Multiple spaces: "+multipleSpaces);

String result=input.replaceAll("\\s{2,}", " ");


System.out.println("Final String : "+result);
}
}

Output:-

57

You might also like