Monday, 10 March 2014

System Calls

// Program to implement  System Calls


#include<stdio.h>
main()
{
int pid;
printf("DATE:(To be printed by child process)\n");
pid=fork();
switch(pid)
{
case -1:printf("FORK FAILED");
exit(1);
case 0:printf("\n CHIELD PROCESS ID IS: %i",getpid());
execl("/bin/date","date",(char*)0);
break;
default:break;
}
wait(10);
printf("\nPARET PROCESS ID: %i \n",getpid());
}


OUTPUT :


guest-vLoOth@computer-OptiPlex-745:~$ cc sc.c

guest-vLoOth@computer-OptiPlex-745:~$ ./a.out

DATE:(To be printed by child process)
Mon Mar 10 14:23:49 IST 2014
PARET PROCESS ID: 2537

Optimal Page Replacement Algorithm



// Program to Implement Optimal Page Replacement Algorithm


#include <stdio.h>

# define infinite 1000


int fdistance(int trace[],int ntrace, int start,int pageno )

  {
    int i;

    for(i=start+1;i<ntrace ;i++)

     if(pageno==trace[i])

       return(i-start);

      return(infinite);
   }


 int search(int a[],int n, int pageno)
   {
     int i;

     for(i=0;i<n;i++)

       if(a[i]==pageno)

     return(1);

     return(0);
   }



  int findmax(int a[],int n)

   {
     int i,j;
     j=0;

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

      if(a[i] > a[j])

     j=i;

     return(j);
   }

 int findempty(int a[],int n)
   {
     int i;
     for(i=0;i<n;i++)
       if(a[i]==-1)
        return(i);
     return(-1);
   }

int main()
 {
    int optf[10],trace[30],ntrace,nframes;

    int i,j,loc,optd[10];

    float opth=0.00;

    printf("\n Enter no. of frames : ");
    scanf("%d",&nframes);

    printf("\n enter no of entries in the page trace : ");
    scanf("%d",&ntrace);

    printf("\nEnter page trace : ");

    for(i=0;i<ntrace;i++)
    scanf("%d",&trace[i]);

    /** initialize frames */

    for(i=0;i<nframes;i++)
     {
    optf[i]=-1;
    optd[i]=0;
     }

 /*allocation */
   printf("\nPage no.     OPT Allocation");

   for(i=0;i<ntrace;i++)

    {

 //OPT
      if(!search(optf,nframes,trace[i]))

    {
        loc=findempty(optf,nframes);

        if(loc!=-1)//Empty Frame

            optf[loc]=trace[i];

        else
           {  
              //Page fault

            loc=findmax(optd,nframes);

            optf[loc]=trace[i];
           }
    }

     else

       //Page Hit,Adjust forward distance

    opth=opth+1;

   for(j=0;j<nframes;j++)

    optd[j]=fdistance(trace,ntrace,i, optf[j]);

//print report

     printf("\n %d        ",trace[i]);

     for(j=0;j<nframes;j++)

       printf("%3d ",optf[j]);


  }

 printf("\npage fault:   %.2f" ,ntrace-opth);
 return (0);

 }

-------------------------------------------------------------------------------------------

output:

[root@localhost ~]# cc opt.c
[root@localhost ~]# ./a.out

 Enter no. of frames : 3

 enter no of entries in the page trace : 12

Enter page trace : 2
3
2
1
5
2
4
5
3
2
5
2

Page no.     OPT Allocation
 2          2  -1  -1
 3          2   3  -1
 2          2   3  -1
 1          2   3   1
 5          2   3   5
 2          2   3   5
 4          4   3   5
 5          4   3   5
 3          4   3   5
 2          2   3   5
 5          2   3   5
 2          2   3   5
page fault:   6.00[root@localhost ~]#


Least Page Replacement Algorithm


 // Program to implement Least Page Replacement Algorithm

 

//Experiment No. 8 :Least Recently Used :

#include <stdio.h>

# define infinite 1000

 int search(int a[],int n, int pageno)
   {
     int i;
     for(i=0;i<n;i++)
    if(a[i]==pageno)
        return(1);
     return(0);
   }

  int findmax(int a[],int n)
   {
     int i,j;
     j=0;
     for(i=1;i<n;i++)
    if(a[i] > a[j])
        j=i;
     return(j);
   }

 int findempty(int a[],int n)
   {
     int i;
     for(i=0;i<n;i++)
    if(a[i]==-1)
        return(i);
     return(-1);
   }

void main()
 {
    int lruf[10],trace[30],ntrace,nframes;
    int i,j,loc,lrud[10];
    float lruh=0.00;
    printf("\n Enter no. of frames : ");
    scanf("%d",&nframes);
    printf("\n enter no of entries in the page trace : ");
    scanf("%d",&ntrace);
    printf("\nEnter page trace : ");
    for(i=0;i<ntrace;i++)
    scanf("%d",&trace[i]);

    /** initialize frames */

    for(i=0;i<nframes;i++)
     {
    lruf[i]=-1;
    lrud[i]=0;
     }

 /*allocation */

   printf("\nPage no.    LRU Allocation");
   for(i=0;i<ntrace;i++)
    {

      if(!search(lruf,nframes,trace[i]))
    {
       loc=findempty(lruf,nframes);
       if(loc!=-1) //Empty frame
         {
        for(j=0;j<nframes;j++)
            lrud[j]++;
        lruf[loc]=trace[i];
        lrud[loc]=0;
         }
      else
        {   //Page Fault
        loc=findmax(lrud,nframes);
        lruf[loc]=trace[i];
        for(j=0;j<nframes;j++)
            lrud[j]++;
        lrud[loc]=0;
        }
    }
       else
       {  //Page Hit,Adjust backward distance
        lruh=lruh+1;
        for(j=0;j<nframes;j++)
          {
            if(lruf[j]!=trace[i])
                lrud[j]++;
            else
                lrud[j]=0;
          }
//Print Report
       }

    printf("\n %d        ",trace[i]);
    for(j=0;j<nframes;j++)
    printf("%3d ",lruf[j],lrud[j]);
   }

 printf("\nHit ratio:   %.2f",lruh/ntrace);
 

 }
/*

************* OUTPUT *************

 Enter no. of frames : 3
 enter no of entries in the page trace : 12

Enter page trace : 2 3 2 1 5 2 4 5 3 2 5 2
Page no.            LRU Allocation
 2                  2  -1  -1
 3                  2   3  -1
 2                  2   3  -1
 1                  2   3   1
 5                  2   5   1
 2                  2   5   1
 4                  2   5   4
 5                  2   5   4
 3                  3   5   4
 2                  3   5   2
 5                  3   5   2
 2                  3   5   2
Hit ratio:   0.42
*/

FIFO Replacement Paging Algorithm


 /* Program to implement FIFO Replacement Paging Algorithm */



#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);

FIFO Replacement Paging Algorithm

return 0;
}

-----------------------------------------------------------------------------

OUTPUT:


guest-stEO95@computer-OptiPlex-745:~$ gedit fifo.c

guest-stEO95@computer-OptiPlex-745:~$ cc fifo.c

guest-stEO95@computer-OptiPlex-745:~$ ./a.out



ENTER THE NUMBER OF PAGES:

9



ENTER THE PAGE NUMBER :

1

2

6

5

3

4

8

9

7



ENTER THE NUMBER OF FRAMES :3

ref string page frames

1 1 -1 -1

2 1 2 -1

6 1 2 6

5 5 2 6

3 5 3 6

4 5 3 4

8 8 3 4

9 8 9 4

7 8 9 7

guest-stEO95@computer-OptiPlex-745:~$

Program to implement System Call


/*Program to implement System Call*/



#include<stdio.h>
main()
{
int pid;
printf("DATE:(To be printed by child process)\n");
pid=fork();
switch(pid)
{
case -1:printf("FORK FAILED");
exit(1);
case 0:printf("\n CHIELD PROCESS ID IS: %i",getpid());
execl("/bin/date","date",(char*)0);
break;
default:break;
}
wait(10);
printf("\nPARET PROCESS ID: %i \n",getpid());
}

OUTPUT :


guest-vLoOth@computer-OptiPlex-745:~$ cc sc.c

guest-vLoOth@computer-OptiPlex-745:~$ ./a.out

DATE:(To be printed by child process)
Mon Mar 10 14:23:49 IST 2014
PARET PROCESS ID: 2537

Tuesday, 4 March 2014

SPOS Banker's Algorithm

// Program to implement Banker's Algorithm



#include<stdio.h>

char res[10]={'A','B','C','D','E','F','G','H','I','J'};

void disp(int m,int n,int alloc[5][5],int max[5][5],int avble[5],int need[5][5]);

void safesq(int m,int n,int alloc[5][5],int avble[5],int need[5][5]);



 main()

{

    int i,j,ch,n,m,work1[5];

    int avble[5],alloc[5][5],max[5][5],need[5][5];

    printf("\nENTER THE NUMBER OF PROCESSES : \t");

    scanf("%d",&n);

    printf("\nENTER THE NUMBER OF RESOURCES : \t");

    scanf("%d",&m);

    printf("\nENTER THE MAXIMUM INSTANCES OF EACH RESOURCE\n");

    for(i=0;i<m;i++)

    {

        printf("\n\tRESOURCE %c:\t",res[i]);

        scanf("%d",&avble[i] );

    }

    printf("\nENTER THE MAXIMUM DEMAND OF EACH PROCESS FOR A RESOURCE\n");

    for(i=0;i<n;i++)

    {

        printf("\n\tFOR PROCESS P%d \n",i);

        for(j=0;j<m;j++)

        {

            printf("\n\tRESOURCE %c : \t",res[j]);

            scanf("%d",&max[i][j]);

        }

    }

    printf("\nENTER THE MAX NO. OF INSTANCES OF A RESOURCE ALLOCATED TO");

    printf(" A PROCESS.\n");

    for(i=0;i<n;i++)

    {

        printf("\n\tFOR PROCESS P%d \n",i);

        for(j=0;j<m;j++)

        {

            printf("\n\tRESOURCE %c : \t",res[j]);

            scanf("%d",&alloc[i][j]);

        }

    }

    for(i=0;i<m;i++)

    {

        work1[i]=0;

        for(j=0;j<n;j++)

        work1[i]+=alloc[j][i];

        avble[i]=avble[i] - work1[i];

    }

    for(i=0;i<n;i++)

    {

        for(j=0;j<m;j++)

        {

            need[i][j]=max[i][j]-alloc[i][j];

        }

    }

    while(1)

    {

        printf("\n\n\tMENU:\n\t1]DISPLAY DATA\n\t2]GENERATE SAFE SEQUENCE");

        printf("\n\t3]EXIT\n\tENTER YOUR CHOICE:\t");

        scanf("%d",&ch);

        switch(ch)

        {

            case 1:

                disp(m,n,alloc,max,avble,need);

                break;

            case 2:

                safesq(m,n,alloc,avble,need);

                break;

           
            case 3:

                exit(0);

            default:

                printf("\n\tINVALID CHOICE ENTERED.\n");

        }

    }

}

void disp(int m,int n,int alloc[5][5],int max[5][5],int avble[5],int need[5][5])

{

    int i,j;

    printf("\n\t\tALLOCATION\tMAX\tNEED\t AVAILABLE");

    printf("\t\t");

    for(i=0;i<4;i++)

    {

        for(j=0;j<m;j++)

            printf("%c ",res[j]);

        printf(" ");

    }

    for(i=0;i<n;i++)

    {

        printf("\n\tP%d\t",i);

        for(j=0;j<m;j++)

            printf("%d ",alloc[i][j]);

        printf(" ");

        for(j=0;j<m;j++)

            printf("%d ",max[i][j]);

        printf("\t");

        for(j=0;j<m;j++)

            printf("%d ",need[i][j]);

        printf(" ");

        if(i==0)

        {

            for(j=0;j<m;j++)

                printf("%d ",avble[j]);

        }

    }

}

void safesq(int m,int n,int alloc[5][5],int avble[5],int need[5][5])

{

    int i,j,k=0,l,work[5],work1[5],fin[5],flag=0,flag1=0,safesq[6];

    for(i=0;i<m;i++)

        work[i]=avble[i];

    for(i=0;i<n;i++)

        fin[i]=0;

    for(l=0;l<n;l++)

    {

        for(i=0;i<n;i++)

        {

            flag1=0;

            if(fin[i]==0)

            {

                for(j=0; j<m; j++)

                {

                    if(need[i][j] > work[j])

                    {

                        flag1=1;

                        break;

                    }

                }

                if(flag1==0)

                {

                    for(j=0;j<m;j++)

                        work[j]=work[j]+alloc[i][j];

                    fin[i]=1;

                    safesq[k]=i;

                    k++;

                }

            }

        }

    }

    for(i=0;i<n;i++)

    {

        if(fin[i]==0)

        {

            printf("\n\tFOR THE GIVEN REQUIREMENT THE SYSTEM IS");

            printf(" NOT IN A SAFE STATE.\n");

            flag=1;

            break;

        }

    }

    if(flag==0)

    {

        printf("\n\tTHE SAFE SEQUENCE IS:\t");

        for(i=0;i<n;i++)

            printf("P%d ",safesq[i]);

    }
}


 ---------------------------------------------------O/P---------------------------------------------------------------

 
computer@computer-OptiPlex-745:~$ cc bka.c
bka.c: In function ‘main’:
bka.c:138:5: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
computer@computer-OptiPlex-745:~$ ./a.out

ENTER THE NUMBER OF PROCESSES : 4

ENTER THE NUMBER OF RESOURCES : 3

ENTER THE MAXIMUM INSTANCES OF EACH RESOURCE

RESOURCE A: 13

RESOURCE B: 7

RESOURCE C: 10

ENTER THE MAXIMUM DEMAND OF EACH PROCESS FOR A RESOURCE

FOR PROCESS P0

RESOURCE A : 4

RESOURCE B : 3

RESOURCE C : 3

FOR PROCESS P1

RESOURCE A : 7

RESOURCE B : 2

RESOURCE C : 4

FOR PROCESS P2

RESOURCE A : 4

RESOURCE B : 2

RESOURCE C : 5

FOR PROCESS P3

RESOURCE A : 5

RESOURCE B : 3

RESOURCE C : 3

ENTER THE MAX NO. OF INSTANCES OF A RESOURCE ALLOCATED TO A PROCESS.

FOR PROCESS P0

RESOURCE A : 2

RESOURCE B : 1

RESOURCE C : 1

FOR PROCESS P1

RESOURCE A : 7

RESOURCE B : 2

RESOURCE C : 3

FOR PROCESS P2

RESOURCE A : 3

RESOURCE B : 2

RESOURCE C : 2

FOR PROCESS P3

RESOURCE A : 1

RESOURCE B : 1

RESOURCE C : 3


MENU:
1]DISPLAY DATA
2]GENERATE SAFE SEQUENCE
3]EXIT
ENTER YOUR CHOICE: 1

ALLOCATION MAX NEED AVAILABLE A B C A B C A B C A B C
P0 2 1 1 4 3 3 2 2 2 0 1 1
P1 7 2 3 7 2 4 0 0 1
P2 3 2 2 4 2 5 1 0 3
P3 1 1 3 5 3 3 4 2 0

MENU:
1]DISPLAY DATA
2]GENERATE SAFE SEQUENCE
3]EXIT
ENTER YOUR CHOICE: 2

THE SAFE SEQUENCE IS: P1 P2 P3 P0

guest-stEO95@computer-OptiPlex-745:~$ gedit 123.c

guest-stEO95@computer-OptiPlex-745:~$ cc 123.c

123.c: In function ‘main’:

123.c:138:17: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]

guest-stEO95@computer-OptiPlex-745:~$ ./a.out

ENTER THE NUMBER OF PROCESSES : 4
ENTER THE NUMBER OF RESOURCES : 3

ENTER THE MAXIMUM INSTANCES OF EACH RESOURCE

RESOURCE A: 2
RESOURCE B: 3
RESOURCE C: 2

ENTER THE MAXIMUM DEMAND OF EACH PROCESS FOR A RESOURCE

FOR PROCESS P0

RESOURCE A : 4
RESOURCE B : 5
RESOURCE C : 3
FOR PROCESS P1

RESOURCE A : 6
RESOURCE B : 3
RESOURCE C : 1

FOR PROCESS P2

RESOURCE A : 4
RESOURCE B : 0
RESOURCE C : 0

FOR PROCESS P3

RESOURCE A : 5
RESOURCE B : 6
RESOURCE C : 1

ENTER THE MAX NO. OF INSTANCES OF A RESOURCE ALLOCATED TO A PROCESS.


FOR PROCESS P0

RESOURCE A : 4
RESOURCE B : 2
RESOURCE C : 0

FOR PROCESS P1

RESOURCE A : 2
RESOURCE B : 3
RESOURCE C : 4

FOR PROCESS P2

RESOURCE A : 2
RESOURCE B : 0
RESOURCE C : 5

FOR PROCESS P3

RESOURCE A : 6
RESOURCE B : 2
RESOURCE C : 3


MENU:

1]DISPLAY DATA

2]GENERATE SAFE SEQUENCE

3]EXIT

ENTER YOUR CHOICE: 1



ALLOCATION MAX NEED AVAILABLE A B C A B C A B C A B C

P0 4 2 0 4 5 3 0 3 3 -12 -4 -10

P1 2 3 4 6 3 1 4 0 -3

P2 2 0 5 4 0 0 2 0 -5

P3 6 2 3 5 6 1 -1 4 -2



MENU:

1]DISPLAY DATA

2]GENERATE SAFE SEQUENCE

3]EXIT

ENTER YOUR CHOICE: 2


FOR THE GIVEN REQUIREMENT THE SYSTEM IS NOT IN A SAFE STATE.








Thursday, 20 February 2014

Producer-Consumer Problem with Multithreading

Producer-Consumer Problem with Multithreading


#define BUFFER_SIZE 10
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define TRUE 1
pthread_mutex_t mutex; //The mutex lock
sem_t full,empty; //semaphores
int buffer[BUFFER_SIZE];
int counter; //buffer counter

pthread_t tid;//ThreadID

void *consumer(void *param);
void *producer(void *param); //The producer thread
void insert_item(int);
int remove_item();
void initialize()
 {
  pthread_mutex_init(&mutex,NULL); //Create the mutex lock
  sem_init(&full,1,0); //Initialize full semaphore to 0
  sem_init(&empty,1,BUFFER_SIZE); //Initialize emty semaphore to BUFFER_SIZE
  counter=0;
 }

/*Producer Thread */

void *producer(void *param)
 {
    int item;
    int waittime;//Next item is produced after waittime
    waittime=rand()% 5;
    sleep(waittime);
    item=rand()%10; //Generate an item to insert in the buffer
    sem_wait(&empty);//wait for queue to become emtpty,using semaphore
    pthread_mutex_lock(&mutex);//Acquire the buffer
    printf("Producer produced %d\n",item);
    insert_item(item);//Insert in the queue
    pthread_mutex_unlock(&mutex); //Release the buffer
    sem_post(&full);//Signal the semaphore full
 }    

/*Consumer thread */

void *consumer(void *param)
 {
  int item;
  int waittime;//Next item is consumed after waittime
  waittime=rand() % 3;
  sleep(waittime);
  sem_wait(&full);//wait if the buffer is full
  pthread_mutex_lock(&mutex);//Acquire the buffer
  item=remove_item();
  printf("Consumer Consumed : %d\n",item);
  pthread_mutex_unlock(&mutex);//Release the buffer
  sem_post(&empty); // Signal empty
 }
 
//Add item to buffer
void insert_item(int item)
 {
   buffer[counter++]=item;
 } 

//Remove an item from the buffer
int remove_item()
 {
    return(buffer[--counter]);
 }

int main()
 {
     int n1;//No. of producers
     int n2;//No. of consumers
     int i;
     printf("Enter no. of producers :\n");
         scanf("%d",&n1);
         printf("Enter no. of consumers :\n");
     scanf("%d",&n2);
     initialize();
   //Create producers threads
        for(i=0;i<n1;i++)
        pthread_create(&tid,NULL,producer,NULL);
  //Create consumer threads            
         for(i=0;i<n2;i++)
         pthread_create(&tid,NULL,consumer,NULL);
      sleep(50);
         exit(0);
 }     

 -----------------------------------------------------------------O/P---------------------------------------------------
guest-stEO95@computer-OptiPlex-745:~$ gedit 1234.c

guest-stEO95@computer-OptiPlex-745:~$ cc 1234.c -lpthread

guest-stEO95@computer-OptiPlex-745:~$ ./a.out

Enter no. of producers :

5

Enter no. of consumers :

4

Producer produced 6

Consumer Consumed : 6

Producer produced 2

Consumer Consumed : 2

Producer produced 7

Consumer Consumed : 7

Producer produced 0

Consumer Consumed : 0

Producer produced 9

guest-stEO95@computer-OptiPlex-745:~$

Reader-Writer Problem with Multithreading

 Reader-Writer Problem with Multithreading


#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
pthread_mutex_t x,wsem; //The mutex lock
int readcount;
pthread_t tid;//ThreadID

void *reader(void *param); //The writer thread

void *writer(void *param); //The writer thread

void initialize()
 {
  pthread_mutex_init(&x,NULL); //Create the mutex lock x
  pthread_mutex_init(&wsem,NULL);//Create the mutex lock wsem
  readcount=0;
 }

/*Reader Thread */

void *reader(void *param)
 {
    int item;
    int waittime;//Next item is produced after waittime
    waittime=rand()% 5;
    printf("Reader trying to enter\n");
    pthread_mutex_lock(&x);
    readcount++;
    if(readcount==1)
           pthread_mutex_lock(&wsem);
    printf("%d readers inside\n",readcount);
    pthread_mutex_unlock(&x);
    sleep(waittime);
    pthread_mutex_lock(&x);
    readcount--;
    if(readcount==0);
        pthread_mutex_unlock(&wsem);
    pthread_mutex_unlock(&x);
    printf("Reader leaving\n");
 }  
  

/*writer thread */

void *writer(void *param)
 {

  int waittime;//Next write after waittime
  waittime=rand() % 3;
  printf("Writer is trying to enter\n");
  pthread_mutex_lock(&wsem);
  printf("Writer inside\n");
  sleep(waittime);
  pthread_mutex_unlock(&wsem);
  printf("Writer leaving\n");
 }



int main()
 {
     int n1;//No. of readers
     int n2;//No. of writers
     int i;
     printf("Enter no. of readers :\n");
         scanf("%d",&n1);

         printf("Enter no. of writers :\n");
     scanf("%d",&n2);
     initialize();
   //Create reader threads
        for(i=0;i<n1;i++)
        pthread_create(&tid,NULL,reader,NULL);
  //Create writer threads           
         for(i=0;i<n2;i++)
         pthread_create(&tid,NULL,writer,NULL);
      sleep(30);
         exit(0);
 } 

OUTPUT: 


guest-stEO95@computer-OptiPlex-745:~$ cc 1235.c -lpthread

guest-stEO95@computer-OptiPlex-745:~$ ./a.out

Enter no. of readers :

5

Enter no. of writers :

4

Reader trying to enter

Reader trying to enter

Reader trying to enter

1 readers inside

Reader trying to enter

Writer is trying to enter

2 readers inside

3 readers inside

Reader trying to enter

4 readers inside

Reader leaving

4 readers inside

Reader leaving

Writer inside

Writer is trying to enter

Writer is trying to enter

Writer is trying to enter

Reader leaving

Writer inside

Reader leaving

Writer inside

Writer leaving

Writer inside

Writer leaving

Writer leaving

Writer leaving

Reader leaving

guest-stEO95@computer-OptiPlex-745:~$


Monday, 17 February 2014

Lab Manual for Computer Graphics


 Lab Manual for SE Computer Graphics



Introduction

Computer graphics deals with all aspects of creating images with a computer

Computer graphics are graphics created using computers and, more generally, the representation and manipulation of image data by a computer. The development of computer graphics, or simply referred to as CG, has made computers easier to interact with, and better for understanding and interpreting many types of data. Developments in computer graphics have had a profound impact on many types of media and have revolutionized the animation and video game industry. Typically, the term computer graphics refers to several different things: · the representation and manipulation of image data by a computer · the various technologies used to create and manipulate images · the images so produced and The subfield of computer science which studies methods for digitally synthesizing and manipulating visual content
Applications of Computer Graphics

  1. Computer-Aided Design for engineering and architectural systems etc.
Objects maybe displayed in a wireframe outline form. Multi-window environment is also favored for producing various zooming scales and views. Animations are useful for testing performance.
  1. Presentation Graphics
To produce illustrations which summarize various kinds of data. Except 2D, 3D graphics are good tools for reporting more complex data.
  1. Computer Art
Painting packages are available. With cordless, pressure-sensitive stylus, artists can produce electronic paintings which simulate different brush strokes, brush widths, and colors.
Photorealistic techniques, morphing and animations are very useful in commercial art. For films,
24 frames per second are required. For video monitor, 30 frames per second are required.
  1. Entertainment
Motion pictures, Music videos, and TV shows, Computer games
  1. Education and Training
Training with computer-generated models of specialized systems such as the training of ship captains and aircraft pilots.
  1. Visualization
For analyzing scientific, engineering, medical and business data or behavior. Converting data to visual form can help to understand mass volume of data very efficiently.
  1. Image Processing
Image processing is to apply techniques to modify or interpret existing pictures. It is widely used in medical applications.
  1. Graphical User Interface
Multiple window, icons, menus allow a computer setup to be utilized more efficiently.
Assignment- 1

1.Study of basic graphics functions defined in “graphics.h”.

Aim : Study of basic graphics functions defined in “graphics.h”.


Graphics mode Initialization
First of all we have to call the initgraph function that will initialize the graphics mode on the computer. initigraph have the following prototype.
void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);
Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into graphics mode. Initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.
*graphdriver Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics_drivers enumeration type.
*graphmode Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type.
*pathtodriver Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.
1. If they‟re not there, initgraph looks in the current directory.
2. If pathtodriver is null, the driver files must be in the current directory.

*graphdriver and *graphmode must be set to valid graphics_drivers and graphics_mode values or you‟ll get unpredictable results. (The exception is graphdriver = DETECT.) After a call to initgraph, *graphdriver is set to the current graphics driver, and *graphmode is set to the current graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to autodetect the attached video adapter at run time and pick the corresponding driver. If you tell initgraph to autodetect, it calls detectgraph to select a graphics driver and mode.
Basic Function :
Cleardevice() Clears all previous graphical outputs generated by the previous programs.Its a good practice to include this method at the starting of each program.
cleardevice()
gotoxy() This will initialize the graphics cusor to the specified co-ordiante.In C gotoxy function is used very frequently to locate the cursor at different locations whenever as necessary. Syntax : gotoxy(x,y)
putpixel() It will colour the pixel specified by the co-ordinates.
Syntax: putpixel(x,y,WHITE)
outtextxy() This method is used to display a text in any position on the screen.The numeric coordinates are substituted for x and y.
Syntax: outtextxy(x,y,"HELLO")
rectangle() Draws a rectangle according to the given parameter x and y are the top-left corner co-ordinates.
Syntax : rectangle(int left, int top, int right, int bottom)
circle() Draws a circle with x,y as the center . Syntax: circle(x,y,radius) line() Draws a line as per the given co-ordinates.
Syntax : line(int startx, int starty, int endx, int endy)
moveto() Cursor is moved from the current location to the specified location dx,dy.These parameters can also be used as incremental values.
Syntax : moveto(dx,dy)
lineto() Draws a line from its current location to the co-ordinate(x,y)
Syntax : lineto(x,y)
ellipse() Draws the ellipse with the specified angles and coordinates.
Syntax : ellipse(x-centre,y-center,starting_angle,ending_angle,x_radius,y_radius) drawpoly() Draws a polygon with (num_of_points +1) edges.The array 'points'
int points[ ]=(x1,y1,x2,y2,x3,y3...)
Syntax : drawpoly(num_of_points + 1, points)
settextstyle() The fonts available are : TRIPLEX_FONT, SMALL_FONT SANS_SERIE_FONT, GOTHIC_FONT The direction can be changed as HORIZ_DIR or VERT_DIR, The charecter size increases from 1 to 10
Syntax : settextstyle(DEFAULT_FONT,HORIZ_DIR,1)
setfillstyle() The fill styles avaliable are SOLID_FILL, LINE_FILL, HATCH_FILL, SLASH_FILL etc.
Syntax : setfillstyle(SOLID_FILL,RED)
setcolor() Sets the color
Syntax : setcolor(color_name)
delay() Cause a pause in execution of the program 1000ms= 1 second
Syntax : delay(100)
closegraph() Terminates all graphics operations and revert the hardware back to the normal mode. 
 ------------------------------------------Program ----------------------------------------------------------------------
Assignment no: 01
Program to study Graphics.h header file
 #include<iostream>
    #include<graphics.h>
  
    int main()
    {
     int gd=DETECT,gm,x,y;
     initgraph(&gd,&gm,NULL);
     line(0,0,100,100);
     getch();
     closegraph();
     return 0;
    }



Assignment no: 02
//Aim:Writing a C/C++ Program to emulate CPU Architecture (Central Bus) Develop register, ALU level GUI to display results.

#include<iostream>
#include<graphics.h>
using namespace std;
int main()
{
int x,y;
int poly[10];
int gd=DETECT,gm=VGAMAX;
initgraph(&gd,&gm,NULL);
setcolor(WHITE);
poly[0]= 50;
poly[1]= 50;

poly[2]= 600;
poly[3]= 50;

poly[4]= 600;
poly[5]= 600;

poly[6]= 50;
poly[7]= 600;

poly[8]=poly[0];
poly[9]=poly[1];
drawpoly(5,poly);
rectangle(65,100,150,140);
outtextxy(95,115,"ALU");
line(150,120,180,120);
rectangle(180,100,380,140);
outtextxy(200,120,"SEQUENCE CONTROLLER");
rectangle(410,100,550,160);
outtextxy(422,107,"GENERAL");
outtextxy(422,122,"PURPOSE");
outtextxy(422,136,"REGISTER");
rectangle(410,220,550,250);
outtextxy(422,228,"CACHE MEMORY");
rectangle(210,180,350,220);
outtextxy(240,190,"PROGRAM");
outtextxy(240,205,"COUNTER");
line(280,140,280,180);
rectangle(65,280,200,250);
outtextxy(85,255,"INSTRUCTION");
outtextxy(85,268,"REGISTER");
rectangle(65,340,200,310);
outtextxy(85,315,"INSTRUCTION");
outtextxy(85,328," DECODER");
line(50,420,600,420);
line(50,450,600,450);
outtextxy(220,430,"ADDRESS & DATA BUS");
outtextxy(190,460,"BASIC ARCHITECTURE OF CPU");
line(105,140,105,250);
line(260,380,260,420);
line(320,380,320,420);
delay(10000);
closegraph();
return 0;
}


Assignment no: 03
//Aim:Writing a C++ class for displaying pixel or point on the screen.

 #include<iostream>
#include<graphics.h>
using namespace std;
class pt
{
private:int xco,yco,color;
public:
      pt()                           // no-argument constructor
       {
         xco=0,yco=0, color=15;
       
       }
       void setco(int x,int y)       // set pixel coordinates
       {
          xco=x;
          yco=y;
       }

       void setcolor(int c)           // set pixel color
       {
        color=c;
       }
 
       void draw()                     // display piont or pixel
       {
        putpixel(xco,yco,color);
       }
};

int main()
{

int gd,gm=VGAMAX; gd=DETECT;          
initgraph(&gd,&gm,NULL);                 // Initialize graphics

pt p1;                                   // creat point

p1.setco(100,100);                       // set coordinates
p1.setcolor(14);                         // set colour
p1.draw();                               // display pixel
p1.setco(110,100);                       // set coordinates
p1.draw();                               // display pixel
p1.setco(120,100);                       // set coordinates
p1.draw();                               // display pixel

getch();                                 // wait for keypress
closegraph();                            // close graphics system
return 0;
}

 Assignment no: 04

 //Write a C++ class for a Line drawing method using overloading DDA and Bresenham’s Algorithms, inheriting the pixel or point.

 

#include<graphics.h>

#include<iostream>

using namespace std;

class pt //base class

{

protected: int xco,yco,color;

public:

pt()

{

xco=0;yco=0;color=15;

}

void setco(int x,int y)

{

xco=x;

yco=y;

}

void setcolor(int c)

{

color=c;

}


void draw()

{ putpixel(xco,yco,color);

}

};

class dline: public pt //derived class

{

private: int x2,y2;


public:

dline():pt()

{

x2=0,y2=0;

}


void setline(int x, int y, int xx, int yy)

{

pt::setco(x,y);

x2=xx;

y2=yy;

}

void drawl() //Bresenham's Line

{

float x,y,dx,dy,e,temp;

int i,s1,s2,ex;


dx=abs(x2-xco);

dy=abs(y2-yco);

x=xco;

y=yco;

pt::setco(x,y);

pt::draw();


if(x2 > xco) //sign() function

{

s1=1;

}

if(x2 < xco)

{

s1=-1;

}

if(x2 == xco)

{

s1=0;

}

if(y2 > yco)

{

s2=1;

}

if(y2 < yco)

{

s2=-1;

}

if(y2 == yco)

{

s2=0;

}

if(dy > dx)

{

temp = dx;

dx = dy;

dy = temp;

ex = 1;

}

else

{

ex=0;

}

e=2*dy-dx; //decision variable

i=1;

do

{

while(e>=0)

{

if(ex==1)

{

x = x + s1;

}

else

{

y = y + s2;

}

e = e + 2*dy - 2*dx;

}

if(ex==1)

{

y = y + s2;

}

else

{

x = x + s1;

}

e = e + 2*dy;


pt::setco(x,y);

pt::draw();

i = i + 1;


}while(i<=dx);

}

void drawl(int colour) //DDA Line

{

float x,y,dx,dy,len;

int i;

pt::setcolor(colour);


dx=abs(x2-xco);

dy=abs(y2-yco);


if(dx >= dy)

{

len=dx;

}

else

{

len=dy;

}

dx=(x2-xco)/len;

dy=(y2-yco)/len;

x = xco + 0.5;

y = yco + 0.5;

i=1;

while(i<=len)

{

pt::setco(x,y);

pt::draw();

x = x + dx;

y = y + dy;

i = i + 1;

cout<<"\ti"<<i;

cout<<"\tx"<<x;

cout<<"\ty "<<y<<endl;


}

pt::setco(x,y);

pt::draw();

}

};

int main()

{

int gd=DETECT,gm=VGAMAX;

int ch,x1,y1,x2,y2, xmax,ymax,xmid,ymid;

char a;

initgraph(&gd,&gm,NULL);

pt p;

dline dda;


xmax = getmaxx();

ymax = getmaxy();

xmid = xmax /2;

ymid = ymax /2;

line(xmid,0,xmid,ymax); //Y co-ordinate

line(0,ymid,xmax,ymid); //X co-ordinate

do

{

xmax = getmaxx();

ymax = getmaxy();

xmid = xmax /2;

ymid = ymax /2;

cout<<"1.DDA LINE..";

cout<<"\n2.BRESENHAM'S LINE..";

cout<<"\n3.EXIT..";

cout<<"\nEnter your choice: ";

cin>>ch;

switch(ch)

{

case 1:

cout<<"\n Enter x1: "; cin>>x1;

cout<<"\n Enter y1: "; cin>>y1;

cout<<"\n Enter x2: "; cin>>x2;

cout<<"\n Enter y2: "; cin>>y2;

dda.setline(x1+xmid,ymid-y1,x2+xmid,ymid-y2);

dda.drawl(15);

break;

case 2:

cout<<"\n Enter x1: "; cin>>x1;

cout<<"\n Enter y1: "; cin>>y1;

cout<<"\n Enter x2: "; cin>>x2;

cout<<"\n Enter y2: "; cin>>y2;

dda.setline(x1+xmid,ymid-y1,x2+xmid,ymid-y2);

dda.drawl();

break;

case 3:

exit;

break;

}

cout<<"\nDO U Want To Continue y OR n: ";

cin>>a;

}while(a!='n');

delay(3000);

getch();

closegraph();

return 0;


}


 Assignment no: 04

 // Write a C++ class for a circle drawing inheriting line class 
 
#include<graphics.h>
#include<iostream>
#include<stdlib.h>
#include<math.h>

using namespace std;

class dline //base class
{
protected: int x0,y0,x1,y1,x2,y2, colour;
public:
dline()
{
x1=0; y1=0; x2=0, y2=0;
}
void setcolor(int color)
{
colour =color;
}

void setoff1(int xx,int yy)
{
x0=xx;
y0=yy;
}
void setline(float x1,float y1, float xx,float yy)
{
x1=x1+x0; y1=y0-y1; x2=xx+x0, y2=y0-yy;
}
void drawl(float x1,float y1, float xx,float yy) //Simple DDA Line
{
float x,y,dx,dy,len;
int i;
dx=abs(x2-x1);
dy=abs(y2-y1);
if(dx >= dy)
{

len=dx;
}
else
{
len=dy;
}
dx=(x2-x1)/len;
dy=(y2-y1)/len;
x = x1 + 0.5;
y = y1 + 0.5;
putpixel(x,y,colour);
x = x + dx;
y = y + dy;
}
};
class mcircle:public dline
{
private: int x0,y0;
public:
mcircle():dline()
{
x0=0;y0=0;
}
void setoff(int xx,int yy)
{
x0=xx;
y0=yy;
}
void drawc(float x1, float y1, int r)
{
int i, x, y;
float d;
x=0, y=r;
d = 1.25 - r; //decision variabel
dline::setline(x,y,x,y);
do
{
dline::drawl(x1+x0+x, y0-y1+y,x1+x0+x, y0-y1+y);
dline::drawl(x1+x0+y, y0-y1+x,x1+x0+y, y0-y1+x);
dline::drawl(x1+x0+y, y0-y1-x,x1+x0+y, y0-y1-x);
dline::drawl(x1+x0+x, y0-y1-y,x1+x0+x, y0-y1-y);
dline::drawl(x1+x0-x, y0-y1-y,x1+x0-x, y0-y1-y);
dline::drawl(x1+x0-y, y0-y1-x,x1+x0-y, y0-y1-x);
dline::drawl(x1+x0-y, y0-y1+x,x1+x0-y, y0-y1+x);
dline::drawl(x1+x0-x, y0-y1+y,x1+x0-x, y0-y1+y);

if(d<0)
{
x = x + 1;
d = d + (2*x) + 3;
}
else
{
x = x + 1;
y = y - 1;
d = d + (2*x-2*y) + 3;
}

}while(x<=y);
}
};


int main()
{
int gd=DETECT,gm=VGAMAX;
int i, x, y, r, xmax,ymax,xmid,ymid;
char a;
initgraph(&gd,&gm,NULL);
dline l;
mcircle c;
xmax = getmaxx();
ymax = getmaxy();
xmid = xmax /2;
ymid = ymax /2;

line(xmid,0,xmid,ymax); //Y co-ordinate
line(0,ymid,xmax,ymid); //X co-ordinate
do
{
cout<<"\n Enter x: "; cin>>x;
cout<<"\n Enter y: "; cin>>y;
cout<<"\n Enter radius: "; cin>>r;
c.setoff(xmid, ymid);
l.setoff1(xmid, ymid);
l.setcolor(15);
c.drawc(x,y,r);
cout<<"\nDO U Want To Continue y OR n: ";
cin>>a;
}while(a!='n');
delay(3000);
getch();
closegraph();
return 0;
}

Assignment no: 05

//Aim:Write a program in C/C++ to draw a circle of desired radius.
 


#include<graphics.h>
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
class dcircle
{
private: int x0,y0;
public:
dcircle()
{
x0=0;y0=0;
}

void setoff(int xx,int yy)
{
x0=xx;
y0=yy;
}

void drawdc(float x, float y, int r) //DDA Circle
{
float x1,y1,x2,y2,startx,starty,ep;
int i,val;

x1=r*cos(0); //Initialize starting point
y1=r*sin(0);
startx = x1;
starty = y1;

i=0;
do
{
val = pow(2,i);
i++;
}while(val<r);
ep = 1/pow(2,i-1); //calculation of epsilon
do
{
x2 = x1 + y1*ep;
y2 = y1 - x2*ep;
putpixel(x0+x+x2, y0-(y+y2),15);
x1 = x2;
y1 = y2;
}while((y1 - starty) < ep || (startx - x1) > ep);
}
void drawbc(int x1, int y1, int r) //Bresenham's Circle
{
int i, x, y;
float d;
x=0, y=r;
d = 3 - 2*r; //decision variable

do
{
putpixel(x1+x0+x, y0-y1+y,15);
putpixel(x1+x0+y, y0-y1+x,15);
putpixel(x1+x0+y, y0-y1-x,15);
putpixel(x1+x0+x, y0-y1-y,15);
putpixel(x1+x0-x, y0-y1-y,15);
putpixel(x1+x0-y, y0-y1-x,15);
putpixel(x1+x0-y, y0-y1+x,15);
putpixel(x1+x0-x, y0-y1+y,15);

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

}while(x<=y);
}
void drawmc(float x1, float y1, int r) // Mid point Circle
{
int i, x, y;
float d;
x=0, y=r;
d = 1.25 - r; //decision variable

do
{
putpixel(x1+x0+x, y0-y1+y,15);
putpixel(x1+x0+y, y0-y1+x,15);

putpixel(x1+x0+y, y0-y1-x,15);
putpixel(x1+x0+x, y0-y1-y,15);
putpixel(x1+x0-x, y0-y1-y,15);
putpixel(x1+x0-y, y0-y1-x,15);
putpixel(x1+x0-y, y0-y1+x,15);
putpixel(x1+x0-x, y0-y1+y,15);

if(d<0)
{
x = x + 1;
d = d + (2*x) + 3;
}
else
{
x = x + 1;
y = y - 1;
d = d + (2*x-2*y) + 5;
}
}while(x<=y);
}
};

int main()
{
int gd=DETECT,gm=VGAMAX;
int i, x, y, r,ch, xmax,ymax,xmid,ymid;
float a,b;
char ans;
initgraph(&gd, &gm, NULL);
dcircle c1;
xmax = getmaxx();
ymax = getmaxy();
xmid = xmax /2;
ymid = ymax /2;

line(xmid,0,xmid,ymax); //Y co-ordinate
line(0,ymid,xmax,ymid); //X co-ordinate
do
{
cout<<"\nEnter Cricle Drwaing algorithm";
cout<<"\n1.DDA..";
cout<<"\n2.BRESENHAM'S..";
cout<<"\n3.MID POINT..";
cout<<"\n4.EXIT..";
cout<<"\nEnter your choice: ";
cin>>ch;
switch(ch)
{
case 1:
{
cout<<"\n Enter x: "; cin>>a;
cout<<"\n Enter y: "; cin>>b;
cout<<"\n Enter radius: "; cin>>r;

c1.setoff(xmid, ymid);
setcolor(15);
c1.drawdc(a,b,r);
break;
}
case 2:
{
cout<<"\n Enter x: "; cin>>x;
cout<<"\n Enter y: "; cin>>y;
cout<<"\n Enter radius: "; cin>>r;

c1.setoff(xmid, ymid);
setcolor(15);
c1.drawbc(x,y,r);
break;
}

case 3:
{
cout<<"\n Enter x: "; cin>>x;
cout<<"\n Enter y: "; cin>>y;
cout<<"\n Enter radius: "; cin>>r;

c1.setoff(xmid, ymid);
setcolor(15);
c1.drawmc(x,y,r);
break;
}
case 4:
exit;
break;
}
cout<<"\nDO U Want To Continue y OR n: ";
cin>>ans;
}while(ans!='n');

delay(3000);
getch();
closegraph();
return 0;
}

Assignment no: 06


//Aim:Write a program using C/C++ to draw a line with line styles (Thick, Thin, Dotted).

//Line styles using DDA

#include<graphics.h>
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
class pt //base class
{
protected: int xco,yco,color;

public:
pt()
{
xco=0;yco=0;color=15;
}
void setco(int x,int y)
{
xco=x;
yco=y;
}
void setcolor(int c)
{
color=c;
}
void draw()
{ putpixel(xco,yco,color);

}

};

class dline: public pt //derived class
{
private: int x2,y2;
public:
dline():pt()
{
x2=0,y2=0;
}
void setline(int x, int y, int xx, int yy)
{
pt::setco(x,y);
x2=xx;
y2=yy;
}

void drawsi(int colour) //Simple DDA Line
{
float x,y,dx,dy,len;
int i;
pt::setcolor(colour);
dx=abs(x2-xco);
dy=abs(y2-yco);
if(dx >= dy)
{
len=dx;
}
else
{
len=dy;
}

dx=(x2-xco)/len;
dy=(y2-yco)/len;

x = xco + 0.5;
y = yco + 0.5;

i=1;
while(i<=len)
{
pt::setco(x,y);
pt::draw();
x = x + dx;
y = y + dy;
i = i + 1;
}
pt::setco(x,y);
pt::draw();
}

void drawda(int colour) //Dash DDA Line
{
float x,y,dx,dy,len;
int i,dash_pixel=0, dash_space=0;
pt::setcolor(colour);
dx=abs(x2-xco);
dy=abs(y2-yco);
if(dx >= dy)
{
len=dx;
}
else
{
len=dy;
}

dx=(x2-xco)/len;
dy=(y2-yco)/len;

x = xco + 0.5;
y = yco + 0.5;

i=1;
while(i<=len)
{
dash_pixel=0;
while(dash_pixel<5)
{
pt::setco(x,y);
pt::draw();
x = x + dx;
y = y + dy;
i = i + 1;
dash_pixel = dash_pixel +1;
}
dash_space=0;
while(dash_space<=2)
{
x = x + dx;
y = y + dy;
i = i + 1;
dash_space = dash_space +1;
}
}
}

void drawdo(int colour) //Dotted DDA Line
{ float x,y,dx,dy,len;
int i,dot_space;
pt::setcolor(colour);
dx=abs(x2-xco);
dy=abs(y2-yco);
if(dx >= dy)
{
len=dx;
}
else
{
len=dy;
}
dx=(x2-xco)/len;
dy=(y2-yco)/len;
x = xco + 0.5;
y = yco + 0.5;
i=1;
while(i<=len)
{
dot_space=0;
while(dot_space<=1)
{
x = x + dx;
y = y + dy;
i = i + 1;
dot_space = dot_space +1;
}
pt::setco(x,y);
pt::draw();
}

}

void drawth(int x1,int y1, int x2, int y2,int colour ) //Thick DDA Line
{
float x,y,dx,dy,len;
int i;
dx=abs(x2-x1);
dy=abs(y2-y1);
if(dx >= dy)
{ len=dx;
}
else
{ len=dy;
}
dx=(x2-x1)/len;
dy=(y2-y1)/len;
x = x1 + 0.5;
y = y1 + 0.5;

i=1;
while(i<=len)
{ putpixel(x,y,colour);
x = x + dx;
y = y + dy;
i = i + 1;
}
putpixel(x,y,colour);

}
};
int main()
{
int gd=DETECT,gm=VGAMAX;
int i, ch,x1,y1,x2,y2, dx,dy,xmax,ymax,xmid,ymid,wx,wy,th;
char a;
initgraph(&gd,&gm,NULL);
dline ls;
xmax = getmaxx();
ymax = getmaxy();
xmid = xmax /2;
ymid = ymax /2;
line(xmid,0,xmid,ymax); //Y co-ordinate
line(0,ymid,xmax,ymid); //X co-ordinate
do
{ xmax = getmaxx();
ymax = getmaxy();
xmid = xmax /2;
ymid = ymax /2;

cout<<"\nEnter Line Styles";
cout<<"\n1.SIMPLE..";
cout<<"\n2.DASH..";
cout<<"\n3.DOTTED..";
cout<<"\n4.THICK..";
cout<<"\n5.EXIT..";
cout<<"\nEnter your choice: ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n Enter x1: "; cin>>x1;
cout<<"\n Enter y1: "; cin>>y1;
cout<<"\n Enter x2: "; cin>>x2;
cout<<"\n Enter y2: "; cin>>y2;
ls.setline(x1+xmid,ymid-y1,x2+xmid,ymid-y2);
ls.drawsi(15);
break;
case 2:
cout<<"\n Enter x1: "; cin>>x1;
cout<<"\n Enter y1: "; cin>>y1;
cout<<"\n Enter x2: "; cin>>x2;
cout<<"\n Enter y2: "; cin>>y2;
ls.setline(x1+xmid,ymid-y1,x2+xmid,ymid-y2);
ls.drawda(15);
break;
case 3:
cout<<"\n Enter x1: "; cin>>x1;
cout<<"\n Enter y1: "; cin>>y1;
cout<<"\n Enter x2: "; cin>>x2;
cout<<"\n Enter y2: "; cin>>y2;
ls.setline(x1+xmid,ymid-y1,x2+xmid,ymid-y2);
ls.drawdo(15);
break;
case 4:
cout<<"\n Enter x1: "; cin>>x1;
cout<<"\n Enter y1: "; cin>>y1;
cout<<"\n Enter x2: "; cin>>x2;
cout<<"\n Enter y2: "; cin>>y2;
cout<<"Enter Thickness: ";
cin>>th;
ls.drawth(x1+xmid,ymid-y1,x2+xmid,ymid-y2,15);
if((y2-y1)/(x2-x1) <1)
{
wy=(th-1)*sqrt(pow((x2-x1),2)+pow((y2-y1),2))/(2*abs(x2-x1));
for(i=0;i<wy;i++)
{
ls.drawth(x1+xmid,ymid-y1-i,x2+xmid,ymid-y2-i,15);
ls.drawth(x1+xmid,ymid-y1+i,x2+xmid,ymid-y2+i,15);
}
}
else
{
wx=(th-1)*sqrt(pow((x2-x1),2)+pow((y2-y1),2))/(2*abs(y2-y1));
for(i=0;i<wx;i++)
{
ls.drawth(x1+xmid-i,ymid-y1,x2+xmid-i,ymid-y2,15);
ls.drawth(x1+xmid+i,ymid-y1,x2+xmid+i,ymid-y2,15);
}
}
break;
case 5:
exit;
break;
}
cout<<"\nDO U Want To Continue y OR n: ";
cin>>a;
}while(a!='n');
delay(3000);
getch();
closegraph();
return 0;
}
 

Assignment no: 07

 //Write a C/C++ program to draw a convex polygons (Square, Rectangle, Triangle).





#include<iostream>

#include<graphics.h>

using namespace std;



class dline

{

protected: int x1,y1,x2,y2;

public:

dline()

{

x1=0,y1=0,x2=0,y2=0;

}

void step1()

{

cout<<"\n Enter x1: ";cin>>x1;

cout<<"\n Enter y1: ";cin>>y1;

}

void step2()

{

cout<<"\n Enter x2: ";cin>>x2;

cout<<"\n Enter y2: ";cin>>y2;

}

void drawl()

{

float x,y,dx,dy,len;

int i;

dx=abs(x2-x1);

dy=abs(y2-y1);

if(dx >= dy)

{



len=dx;

}

else

{

len=dy;

}



dx=(x2-x1)/len;

dy=(y2-y1)/len;



x = x1 + 0.5;

y = y1 + 0.5;



i=1;



while(i<=len)

{

putpixel(x,y,15);

x = x + dx;

y = y + dy;

i = i + 1;

}



putpixel(x,y,15);



}

};



class rect: public dline //Rectangle

{

private: int w,l;

public:

void setrect()

{

dline::step1();

cout<<"\n Enter width: ";cin>>w;

cout<<"\n Enter length: ";cin>>l;

}

void drawrect()

{

x2=x1;

y2=y1+w;

dline::drawl(); //left



x2=x1+l;

y2=y1;

dline::drawl(); //top



x1=x1;

y1=y1+w;

x2=x1+l;

y2=y1;

dline::drawl(); //bottom



x1=x1+l;

y1=y1-w;

x2=x1;

y2=y1+w;

dline::drawl(); //right

}

};



class square: public dline //Square

{

private: int l;

public:

void setsquare()

{

dline::step1();

cout<<"\n Enter length: ";cin>>l;

}

void drawsquare()

{

x2=x1;

y2=y1+l;

dline::drawl(); //left



x2=x1+l;

y2=y1;

dline::drawl(); //top



x1=x1;

y1=y1+l;

x2=x1+l;

y2=y1;

dline::drawl(); //bottom



x1=x1+l;

y1=y1-l;

x2=x1;

y2=y1+l;

dline::drawl(); //right

}

};

class triangle: public dline //Triangle

{

private: int x3,y3;

public:

void settri()

{

dline::step1();

dline::step2();

cout<<"\n Enter x3: ";cin>>x3;

cout<<"\n Enter y3: ";cin>>y3;

}

void drawtri()

{

int tempx,tempy;

dline::drawl();



tempx=x2;

x2=y2;

x2=x3;

y2=y3;

dline::drawl();



x1=tempx;

y1=tempy;

dline::drawl();

}

};



int main()

{

int gd=DETECT,gm=VGAMAX;

int i, x, y, r,ch, xmax,ymax,xmid,ymid;

char a;

initgraph(&gd,&gm,NULL);

rect r1;

square s;

triangle t;

do

{

cout<<"\nChoose polygon to draw";

cout<<"\n1.Rectangle..";

cout<<"\n2.Square..";

cout<<"\n3.Triangle..";

cout<<"\n4.EXIT..";

cout<<"\nEnter your choice: ";

cin>>ch;

switch(ch)

{

case 1:

{

r1.setrect();

r1.drawrect();

break;

}

case 2:

{

s.setsquare();

s.drawsquare();

break;

}



case 3:

{

t.settri();

t.drawtri();

delay(3000);

break;

}

case 4:

exit;

break;

}

cout<<"\nDO U Want To Continue y OR n: ";

cin>>a;

}while(a!='n');

delay(3000);

getch();

closegraph();

return 0;

}
 

Assignment no: 08

 //Write a C/C++ program to draw a convex polygons (Square, Rectangle, Triangle) using programmable edges.



#include<iostream>

#include<graphics.h>

using namespace std;



class dline

{

protected: int x1,y1,x2,y2;

public:

dline()

{

x1=0,y1=0,x2=0,y2=0;

}

void drawl()

{

float x,y,dx,dy,len;

int i;

dx=abs(x2-x1);

dy=abs(y2-y1);

if(dx >= dy)

{



len=dx;

}

else

{

len=dy;

}



dx=(x2-x1)/len;

dy=(y2-y1)/len;



x = x1 + 0.5;

y = y1 + 0.5;



i=1;



while(i<=len)

{

putpixel(x,y,15);

x = x + dx;

y = y + dy;

i = i + 1;

}



putpixel(x,y,15);



}

};



class poly: public dline //poly

{

private: int a[10][2],p;

public:

void setpts(int i)

{

int j;

for(j=0;j<i;j++)

{

cout<<"\n Enter x-coordinate: "<<j<<":";cin>>a[j][0];

cout<<"\n Enter y-coordinate: "<<j<<":";cin>>a[j][1];

}

}

void drawpoly(int i)

{

int j;

x1=a[0][0];

y1=a[0][1];

x2=a[1][0];

y2=a[1][1];

dline::drawl();

for(j=0;j<i-1;j++)

{

x1=a[j][0];

y1=a[j][1];

x2=a[j+1][0];

y2=a[j+1][1];

dline::drawl();

}



x1=a[j][0];

y1=a[j][1];

x2=a[0][0];

y2=a[0][1];

dline::drawl();

}

};



int main()

{

int n ,gd=DETECT,gm=VGAMAX;

initgraph(&gd,&gm,NULL);

poly shape;

cout<<"\nEnter number of slides: "; cin>>n;

shape.setpts(n);

shape.drawpoly(n);

delay(3000);

getch();

closegraph();

return 0;

}
 

Assignment no: 09

// Write a C/C++ program to fill polygon using scan line algorithm.


//Scan line algorithm for filling polygon 

#include<iostream>
#include<graphics.h>
#include<stdlib.h>
using namespace std;

struct edge
{
int x1,y1,x2,y2,flag;
};


int main()
{
int n,i,j,k,gd=DETECT,gm=VGAMAX, x[10],y[10],ymax=0,ymin=480,yy,temp;
struct edge ed[10],temped;
float dx,dy,m[10],x_int[10],inter_x[10];
initgraph(&gd,&gm,NULL);
cout<<"\n Enter the number of vertices of the graph: "; cin>>n;
cout<<"\n Enter the vertices: \n";
for(i=0;i<n;i++)
{
cout<<"x"<<i<<":"; cin>>x[i];
cout<<"y"<<i<<":"; cin>>y[i];
if(y[i]>ymax)
ymax=y[i];
if(y[i]<ymin)
ymin=y[i];
ed[i].x1=x[i];
ed[i].y1=y[i];
}

for(i=0;i<n-1;i++) //store the edge information
{
ed[i].x2=ed[i+1].x1;
ed[i].y2=ed[i+1].y1;
ed[i].flag=0;
}
ed[i].x2=ed[0].x1;
ed[i].y2=ed[0].y1;
ed[i].flag=0;

for(i=0;i<n-1;i++) //check for y1>y2 if not interchange it
{
if(ed[i].y1<ed[i].y2)
{
temp=ed[i].x1;
ed[i].x1=ed[i].x2;
ed[i].x2=temp;
temp=ed[i].y1;
ed[i].y1=ed[i].y2;
ed[i].y2=temp;
}
}
for(i=0;i<n;i++) //draw polygon
{
line(ed[i].x1,ed[i].y1,ed[i].x2,ed[i].y2);
}
for(i=0;i<n-1;i++) //storing the edges as y1,y2,x1
{
for(j=0;j<n-1;j++)
{
if(ed[j].y1<ed[j+1].y1)
{
temped=ed[j];
ed[j]=ed[j+1];
ed[j+1]=temped;
}
if(ed[j].y1==ed[j+1].y1)
{
if(ed[j].y2<ed[j+1].y2)
{
temped=ed[j];
ed[j]=ed[j+1];
ed[j+1]=temped;
}
if(ed[j].y2==ed[j+1].y2)
{
if(ed[j].x1<ed[j+1].x1)
{
temped=ed[j];
ed[j]=ed[j+1];
ed[j+1]=temped;
}
}
}
}
}

for(i=0;i<n;i++) //calculate 1/slope
{
dx=ed[i].x2-ed[i].x1;
dy=ed[i].y2-ed[i].y1;
if(dy==0)
m[i]=0;
else
m[i]=dx/dy;
inter_x[i]=ed[i].x1;

}
yy=ymax;
while(yy>ymin) //Mark active edges
{
for(i=0;i<n;i++)
{
if(yy>ed[i].y2 && yy<=ed[i].y1 && ed[i].y1!=ed[i].y2)
ed[i].flag=1;
else
ed[i].flag=0;
}

j=0;
for(i=0;i<n;i++) //Finding x intersections
{
if(ed[i].flag==1)
{
if(yy==ed[i].y1)
{
x_int[j]=ed[i].x1;
j++;
if(ed[i-1].y1==yy&&ed[i-1].y1<yy)
{
x_int[j]=ed[i].x1;
j++;
}
if(ed[i+1].y1==yy&&ed[i+1].y1<yy)
{
x_int[j]=ed[i].x1;
j++;
}
}
else
{
x_int[j]=inter_x[i]+(-m[i]);
inter_x[i]=x_int[j];
j++;
}

Assignment no:10

//Write a program in Java/ Python to draw a line with line style (Thick, Thin, Dotted).

import java.awt.*;
import javax.swing.*;

public class Lines extends JFrame{
public Lines(){
super("Line Styles");
setSize(400,400);
setVisible(true);
}

Stroke[] linestyles=new Stroke[]{
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL),
new BasicStroke(25.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER),
new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND),};

Stroke thindashed=new BasicStroke(2.0f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL,1.0f, new float[] {8.0f,3.0f,2.0f,3.0f},0.0f);
final static float dash1[]={10.0f};
final static BasicStroke dashed =new BasicStroke(1.0f, BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
final static float thick1[]={10.0f};
final static BasicStroke thickdash =new BasicStroke(10.0f, BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER, 10.0f, thick1, 0.0f);

public void paint(Graphics g){
int xpoints[]={220,350,350,220};
int ypoints[]={220,220,320,320};
int npoints=4;

int xpoints1[]={60,120,180};
int ypoints1[]={320,220,320};
int npoints1=3;

Graphics2D g2d = (Graphics2D) g;
super.paint(g);
((Graphics2D)g).setStroke(dashed);
g.setColor(Color.red);
g2d.drawLine(50,50,200,50);
g2d.setColor(Color.black);
g.drawString("Dashed Line", 210,55);
((Graphics2D)g).setStroke(thindashed);
g.setColor(Color.blue);
g2d.drawLine(50,90,200,90);
g2d.setColor(Color.black);
g.drawString("Thin Dashed Line", 210,95);

((Graphics2D)g).setStroke(thickdash);
g.setColor(Color.green);
g2d.drawLine(50,130,200,130);
g2d.setColor(Color.black);
g.drawString("Thick Dashed Line", 210,135);

((Graphics2D)g).setStroke(linestyles[0]);
g.setColor(Color.red);
g2d.drawLine(50,170,200,170);
g2d.setColor(Color.black);
g.drawString("Line", 210,175);

}

public static void main(String[] args){
Lines application = new Lines();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Assignment no:11

 //Aim:Write a program in Java to draw a concave polygon.

import java.awt.*;
import javax.swing.*;

public class Polygon extends JFrame{
public Polygon(){
super("Draw Square, Rectangle, Polygon");
setSize(400,400);
setVisible(true);
}

public void paint(Graphics g){
int xpoints[]={55,145,55,145,55};
int ypoints[]={55,55,145,145,55};
int npoints=5;

int xpoints1[]={250,300,350};
int ypoints1[]={100,50,100};
int npoints1=3;

Graphics2D g2d = (Graphics2D) g;
super.paint(g);
g.setColor(Color.red);
g.drawRect(55,150,90,150);
g.drawRect(150,150,200,200);
g2d.setColor(Color.blue);
g2d.drawLine(150,150,150,150);
g.drawPolygon(xpoints,ypoints,npoints);
g.drawPolygon(xpoints1,ypoints1,npoints1);
}

public static void main(String[] args){
Polygon application = new Polygon();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}



Assignment no:12






//Aim: Draw a line using OpenGL

//DDA
 

#include <GL/glut.h>
#include <math.h>
#include <stdio.h>
const float PI=3.14;

void LineWithDDA(int x0,int y0,int x1,int y1)
{
glPointSize(2.0);
glBegin(GL_POINTS);
glColor3f(0.0,0.0,0.0);

int dx,dy,steps,i;
float x,y;
float xinc,yinc;

dy=y1-y0;
dx=x1-x0;
y=y0;
x=x0;
if(abs(dx)>=abs(dy))
{
steps=dx;
}
else
{
steps=dy;
}
xinc=(float)dx/steps;
yinc=(float)dy/steps;
glVertex2d(x,y);
for(i=1;i<steps;i++)
{
x+=xinc;
y+=yinc;
x0=floor(x);
y0=floor(y);
glVertex2d(x,y);
}
glEnd();
}

void init(void)
{
glClearColor(1.0,1.0,1.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0,800,0,600,0,600);
}

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);

LineWithDDA(0,0,800,600);

glutSwapBuffers();
}


int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(800,600);
glutInitWindowPosition(100,100);
glutCreateWindow("DDA Line Drawing!");
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}