/* Write C++ program to draw man walking in the rain with an umbrella. */
#include <iostream>
#include <stdlib.h>
#include <graphics.h>
#include <math.h>
#include <dos.h>
using namespace std;
int main()
{
int gd=DETECT,gm;
int rhx,rhy,j,i;
clrscr();
initgraph(&gd,&gm,NULL);
for(i=0;i<500;i+=5)
{
line(20,380,580,380); //platform
if(i%2==0)
{
line(25+i,380,35+i,340); //leftleg
line(45+i,380,35+i,340);//right leg
line(35+i,310,25+i,330);//left hand
delay(20);
}
else
{
line(35+i,380,35+i,340);
line(35+i,310,40+i,330);
delay(20);
}
line(35+i,340,35+i,310); //body
circle(35+i,300,10); //head
line(35+i,310,50+i,330); // hand
line(50+i,330,50+i,280); //umbrella stick
line(15+i,280,85+i,280); //umbrella right
arc(50+i,280,0,180,35); //umbrella body
arc(55+i,330,180,360,5);//umbrella handle
rhx=getmaxx();
rhy=getmaxy();
for(j=0;j<100;j++)
{
outtextxy(random(rhx),random(rhy-50),"|");
setcolor(WHITE);
}
delay(150);
cleardevice();
return 0;
}
}
Monday, January 11, 2021
Write C++ program to draw man walking in the rain with an umbrella.
Code For Sunrise and Sunset: Using Graphics Library
//Code For Sunrise and Sunset:
#include<iostream>
#include<stdlib.h>
#ifdef __APPLE__
#include<openGL/openGL.h>
#include<GLUT/glut.h>
#else
#include<GL/glut.h>
#endif
using namespace std;
float ballX = -0.8f;
float ballY = -0.3f;
float ballZ = -1.2f;
float colR=3.0;
float colG=1.5;
float colB=1.0;
float bgColR=0.0;
float bgColG=0.0;
float bgColB=0.0;
static int flag=1;
void drawBall(void) {
glColor3f(colR,colG,colB); //set ball colour
glTranslatef(ballX,ballY,ballZ); //moving it toward the screen a
//bit on creation
glutSolidSphere (0.05, 30, 30); //create ball.
}
void drawAv(void) {
glBegin(GL_POLYGON);
glColor3f(1.0,1.0,1.0);
glVertex3f(-0.9,-0.7,-1.0);
glVertex3f(-0.5,-0.1,-1.0);
glVertex3f(-0.2,-1.0,-1.0);
glVertex3f(0.5,0.0,-1.0);
glVertex3f(0.6,-0.2,-1.0);
glVertex3f(0.9,-0.7,-1.0);
glEnd();
}
void drawClouds(){}
void keyPress(int key, int x, int y)
{
if(key==GLUT_KEY_RIGHT)
ballX -= 0.05f;
if(key==GLUT_KEY_LEFT)
ballX += 0.05f;
glutPostRedisplay();
}
void initRendering() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING); //Enable lighting
glEnable(GL_LIGHT0); //Enable light #0
glEnable(GL_LIGHT1); //Enable light #1
glEnable(GL_NORMALIZE); //Automatically normalize normals
//glShadeModel(GL_SMOOTH); //Enable smooth shading
}
//Called when the window is resized
void handleResize(int w, int h) {
//Tell OpenGL how to convert from coordinates to pixel values
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective
//Set the camera perspective
glLoadIdentity(); //Reset the camera
gluPerspective(45.0, //The camera angle
(double)w / (double)h, //The width-to-height ratio
1.0, //The near z clipping coordinate
200.0); //The far z clipping coordinate
}
void drawScene()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glClearColor(bgColR,bgColG,bgColB,0.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Add ambient light
GLfloat ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f}; //Color (0.2, 0.2, 0.2)
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);
//Add positioned light
GLfloat lightColor0[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Color (0.5, 0.5, 0.5)
GLfloat lightPos0[] = {4.0f, 0.0f, 8.0f, 1.0f}; //Positioned at (4, 0, 8)
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);
//Add directed light
GLfloat lightColor1[] = {0.5f, 0.2f, 0.2f, 1.0f}; //Color (0.5, 0.2, 0.2)
//Coming from the direction (-1, 0.5, 0.5)
GLfloat lightPos1[] = {-1.0f, 0.5f, 0.5f, 0.0f};
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1);
glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);
//drawing the SUN
glPushMatrix();
drawBall();
glPopMatrix();
//drawing the Mount Avarest
glPushMatrix();
drawAv();
glPopMatrix();
//drawing the Clouds
glPushMatrix();
drawClouds();
glPopMatrix();
glutSwapBuffers();
}
//float _angle = 30.0f;
void update(int value) {
if(ballX>0.9f)
{
ballX = -0.8f;
ballY = -0.3f;
flag=1;
colR=2.0;
colG=1.50;
colB=1.0;
bgColB=0.0;
}
if(flag)
{
ballX += 0.001f;
ballY +=0.0007f;
colR-=0.001;
//colG+=0.002;
colB+=0.005;
bgColB+=0.001;
if(ballX>0.01)
{
flag=0;
}
}
if (!flag)
{
ballX += 0.001f;
ballY -=0.0007f;
colR+=0.001;
colB-=0.01;
bgColB-=0.001;
if(ballX<-0.3)
{
flag=1;
}
}
glutPostRedisplay(); //Tell GLUT that the display has changed
//Tell GLUT to call update again in 25 milliseconds
glutTimerFunc(25, update, 0);
}
int main(int argc,char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(400,400);
glutCreateWindow("Sun");
initRendering();
glutDisplayFunc(drawScene);
glutFullScreen();
glutSpecialFunc(keyPress);
glutReshapeFunc(handleResize);
glutTimerFunc(25, update, 0);
glutMainLoop();
return(0);
}
Cpp program to generate fractal pattern using Koch Curve
//Cpp program to generate fractal pattern using Koch Curve
#include<graphics.h>
#include<iostream>
#include<math.h>
using namespace std;
void koch(int x1, int y1, int x2, int y2, int it)
{
float angle = 60*M_PI/180;
int x3 = (2*x1+x2)/3;
int y3 = (2*y1+y2)/3;
int x4 = (x1+2*x2)/3;
int y4 = (y1+2*y2)/3;
int x = x3 + (x4-x3)*cos(angle)+(y4-y3)*sin(angle);
int y = y3 - (x4-x3)*sin(angle)+(y4-y3)*cos(angle);
if(it > 0)
{
koch(x1, y1, x3, y3, it-1);
koch(x3, y3, x, y, it-1);
koch(x, y, x4, y4, it-1);
koch(x4, y4, x2, y2, it-1);
}
else
{
line(x1, y1, x3, y3);
line(x3, y3, x, y);
line(x, y, x4, y4);
line(x4, y4, x2, y2);
}
}
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm,NULL);
int x1 = 100, y1 = 100, x2 = 400, y2 = 400;
koch(x1, y1, x2, y2, 4);
delay(5000);
closegraph();
return 0;
}
a) Write C++ program to draw 2-D object and perform following basic transformations, Scaling b) Translation c) Rotation
/* a) Write C++ program to draw 2-D object and perform following basic transformations, Scaling
b) Translation c) Rotation. */
#include<iostream>
#include<graphics.h>
#include<math.h>
using namespace std;
void disp(int n,float c[][3])
{
float maxx,maxy;
int i;
maxx=getmaxx(); //to get maximum x-coordinate value
maxy=getmaxy(); //to get maximum y-coordinate value
maxx=maxx/2;
maxy=maxy/2;
i=0;
//draw polygon
while(i<n-1)
{
line(maxx+c[i][0],maxy-c[i][1],maxx+c[i+1][0],maxy-c[i+1][1]);
i++;
}
i=n-1;
line(maxx+c[i][0],maxy-c[i][1],maxx+c[0][0],maxy-c[0][1]);
//draw xy-axis
setcolor(GREEN);
line(0,maxy,(maxx*2),maxy);
line(maxx,0,maxx,maxy*2);
setcolor(WHITE);
}
void mul(int n,float b[][3],float c[][3],float a[][3])
{
int i,j,k;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=0; //initialize all co-ordinate as 0
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(k=0;k<n;k++)
{
a[i][j]=a[i][j]+(c[i][k]*b[k][j]);
}
}
}
}
void translation(int n,float c[][3],float tx,float ty)
{
float b[10][3],a[10][3];
int i=0,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=0;
}
}
b[0][0]=1;
b[1][1]=1;
b[2][0]=tx;
b[2][1]=ty;
b[2][2]=1;
mul(n,b,c,a);
setcolor(RED);
disp(n,a);
getch();
}
void scaling(int n,float c[][3],float sx,float sy)
{
float b[10][3],a[10][3];
int i=0,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=0;
}
}
b[0][0]=sx;
b[1][1]=sy;
b[2][2]=1;
mul(n,b,c,a);
setcolor(RED);
disp(n,a);
getch();
}
void rotation(int n,float c[][3],float ra)
{
int i=0,j;
float b[10][3],xp,yp,a[10][3];
xp=c[0][0];
yp=c[0][1];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
b[i][j]=0;
}
}
b[0][0]=b[1][1]=cos(ra*3.14/180);
b[0][1]=sin(ra*3.14/180);
b[1][0]=-sin(ra*3.14/180);
b[2][0]=(-xp*cos(ra*3.14/180))+(yp*sin(ra*3.14/180))+xp;
b[2][1]=(-xp*sin(ra*3.14/180))-(yp*cos(ra*3.14/180))+yp;
b[2][2]=1;
mul(n,b,c,a);
setcolor(RED);
disp(n,a);
getch();
}
int main()
{
int i,cho,n,gd=DETECT,gm;
float c[10][3],tx,ty,sx,sy,ra;
cout<<"\n Enter the number of vertices:";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\n Enter the co-ordinates of the vertex"<<i+1<<":";
cin>>c[i][0]>>c[i][1];
c[i][2]=1;
}
do
{
//cleardevice();
cout<<"\n\t******Menu for transformation*******";
cout<<"\n\t 1)Translation";
cout<<"\n\t 2)Scaling";
cout<<"\n\t 3)Rotation";
cout<<"\n\t 4)Exit";
cout<<"\n\t Enter your choice:";
cin>>cho;
switch(cho)
{
case 1:
cout<<"Enter translation factor for x and y axis:";
cin>>tx>>ty;
initgraph(&gd,&gm,NULL);
//clrscr();
//ssscleardevice();
setcolor(BLUE);
disp(n,c);
translation(n,c,tx,ty);
getch();
break;
case 2:
cout<<"Enter scaling factor for x and y axis:";
cin>>sx>>sy;
initgraph(&gd,&gm,NULL);
//clrscr();
//cleardevice();
setcolor(BLUE);
disp(n,c);
scaling(n,c,sx,sy);
getch();
break;
case 3:
cout<<"Enter rotation factor :";
cin>>ra;
initgraph(&gd,&gm,NULL);
//clrscr();
//cleardevice();
setcolor(BLUE);
disp(n,c);
rotation(n,c,ra);
getch();
break;
case 4:
exit(0);
break;
default:
cout<<"\n Invalid choice";
break;
}
}while(cho!=4);
getch();
closegraph();
return 0;
}
Write C++ program to draw the pattern. Use DDA line and Bresenham‘s circle drawing algorithm.
// Write C++ program to draw the pattern. Use DDA line and Bresenham‘s circle drawing algorithm.
# include <graphics.h> //graphics.h library is used to include graphical operations in a program.
# include <math.h>
# include <iostream>
using namespace std ;
void DDALine(int x1,int y1,int x2,int y2,int Color); //declare function
int main()
{
int x1,y1,x2,y2,r,r1,Color;
int gd,gm; gd=DETECT; //Initialize the variables for the graphics driver and graphics mode
// gm is Graphics mode which is a computer display mode that generates image using pixels.
// DETECT is a macro defined in "graphics.h" header file
initgraph(&gd,&gm,NULL); // initgraph initializes the graphics system by loading a graphics driver from disk
cleardevice(); // The header file graphics.h contains cleardevice() function which clears the screen in graphics mode and sets the current position to (0,0)
//call function
DDALine(100,113,50,200,4); //x1,y1,x2,y2,value of color
DDALine(50,200,150,200,4);
DDALine(150,200,100,113,4);
r=50/sqrt(3); //formula to find out radius of small circle
x1=(100+50+150)/3;
y1=(113+200+200)/3;
circle(x1,y1,r); //draw small circle
r1=100/sqrt(3); //formula to find out radius of outer circle
circle(x1,y1,r1); //draw outer circle
delay(10000); //delay() function is used to hold the program's execution for given number of milliseconds
return 0;
}
// define function
void DDALine(int x1,int y1,int x2,int y2,int Color)
{
float dX,dY,Steps;
float xInc,yInc,i,x,y;
dX = x2 - x1;
dY = y2 - y1;
if (abs(dX) > abs(dY))
{
Steps = abs(dX);
}
else
{
Steps = abs(dY);
}
xInc = dX/Steps;
yInc = dY/Steps;
x = x1;
y = y1;
for (i=1;i<=Steps; i++)
{
putpixel(x,y,Color);//The header file graphics. h contains putpixel() function which plots a pixel at location (x, y)of specified color
x = x+xInc;
y=y+yInc;
}
}
Program to implement Cohen-Sutherland Line Clipping Algorithm in C++
/* Program to implement Cohen-Sutherland Line Clipping Algorithm in C++ */
#include<iostream>
#include<graphics.h> //graphics.h library is used to include graphical operations in a program.
using namespace std;
static int LEFT=1,RIGHT=2,BOTTOM=4,TOP=8,xmin,ymin,xmax,ymax;
// getcode fun to find out code of end points of line
int getcode(int x,int y) //x,y cordinates of first endpoint of line
{
int code = 0;
//Perform Bitwise OR to get outcode
if(y > ymax) code |=TOP;
if(y < ymin) code |=BOTTOM;
if(x < xmin) code |=LEFT;
if(x > xmax) code |=RIGHT;
return code;
}
int main()
{
int gd = DETECT,gm;//Initialize the variables for the graphics driver and graphics mode
// gm is Graphics mode which is a computer display mode that generates image using pixels.
// DETECT is a macro defined in "graphics.h" header file
cout<<"Enter the window's minimum and maximum values: ";
cin>>xmin>>ymin >>xmax>>ymax;
int x1,y1,x2,y2;
cout<<"Enter the endpoints of the line: ";
cin>>x1>>y1>>x2>>y2;
initgraph(&gd,&gm,NULL); //initgraph initializes the graphics system by loading a graphics driver from disk
rectangle(xmin,ymin,xmax,ymax); // draw rectanguler window
setcolor(BLUE);
line(x1,y1,x2,y2); //Draw line to be clipped
int outcode1=getcode(x1,y1), outcode2=getcode(x2,y2);
int accept = 0; //decides if line is to be drawn
while(1){
float m =(float)(y2-y1)/(x2-x1);
//Both points inside. Accept line
if(outcode1==0 && outcode2==0){ //The logical AND operator (&&) returns true if both operands are true and returns false otherwise.
accept = 1;
break;
}
//bitwise AND of both codes != 0.Line is outside. Reject line
else if((outcode1 & outcode2)!=0){
break;
}else{
int x,y,temp;
//Decide if point1 is inside, if not, calculate intersection
if(outcode1==0)
temp = outcode2;
else
temp = outcode1;
//Line clips top edge
if(temp & TOP){ //if bitwise of temp and top is true
x = x1+ (ymax-y1)/m; //using this formula perform intersection with top boundry
y = ymax;
}
else if(temp & BOTTOM){ //Line clips bottom edge
x = x1+ (ymin -y1)/m;
y = ymin ;
}else if(temp & LEFT){ //Line clips left edge
x = xmin;
y = y1+ m*(xmin-x1);
}else if(temp & RIGHT){ //Line clips right edge
x = xmax;
y = y1+ m*(xmax-x1);
}
//Check which point we had selected earlier as temp, and replace its co-ordinates
if(temp == outcode1){
x1 = x;
y1 = y;
outcode1 = getcode(x1,y1);
}else{
x2 = x;
y2 = y;
outcode2 = getcode(x2,y2);
}
}
}
cout<<"After clipping:";
if(accept)
cleardevice();
setcolor(WHITE);
rectangle(xmin,ymin,xmax,ymax);
setcolor(RED);
line(x1,y1,x2,y2);
getch();
closegraph();
return 0;
}
Write C++ program to draw a concave polygon and fill it with desired color using scan fill algorithm.
// Write C++ program to draw a concave polygon and fill it with desired color using scan fill algorithm.
#include<iostream>
#include<graphics.h> //graphics.h library is used to include graphical operations in a program.
#include<math.h>
using namespace std;
class scan
{
public:
int x[20],y[20],k;
float slope[20],x_int[20];
void polygon(int n);
};
void scan::polygon(int n)
{
int i;
float dx,dy;
x[n]=x[0];
y[n]=y[0];
for(int i=0;i<n;i++) //draw all lines (edges of polygon)
{
line(x[i],y[i],x[i+1],y[i+1]); // line cordinates x1,y1,x2,y2
}
for(i=0;i<n;i++) // finding slope of all lines
{
dy=y[i+1]-y[i]; // dy=y2-y1
dx=x[i+1]-x[i]; // dx=x2-x1
if(dy==0)
slope[i]=1;
else if(dx==0)
slope[i]=0;
else
slope[i]=dx/dy;
}
// finding intersection points
for(int p=0;p<480;p++) // consider 480 horizontal lines on screen
{
k=0;
for(i=0;i<n;i++)
{
if(( (y[i]<=p) && (y[i+1]>p)) || ((y[i]>p) && (y[i+1]<=p) ))
{
x_int[k]=x[i]+slope[i]*(p-y[i]); // find out intersection points using formula
k++;
}
}
for(int j=0;j<k-1;j++) // perform sorting of intersection points on x direction
{
for(int i=0;i<k-1;i++)
{
if(x_int[i]>x_int[i+1])
{
int temp = x_int[i];
x_int[i] = x_int[i+1];
x_int[i+1] = temp;
}
}
}
for(int i=0;i<k;i=i+2) //fill points of line that are interior to polygon
{
setcolor(YELLOW);
line(x_int[i], p ,x_int[i+1], p); // x1,y1,x2,y2
delay(10);
}
}
}
int main()
{
int n,i;
scan p;
cout<<"Enter edge : \t";
cin>>n;
cout<<"\n\nEnter Coordinates : \t";
for(i=0;i<n;i++)
{
cin>>p.x[i]>>p.y[i];
}
int gd,gm;
gd=DETECT;
initgraph(&gd,&gm,NULL);
p.polygon(n);
getch();
closegraph();
return 0;
}
/* Enter edge : 4
Enter Coordinates :
50 100
100 50
300 200
150 120 Enter edge : 4
Enter Coordinates : 200 300
300 400
200 400
300 300
Enter edge : 4
200 300
300 200
300 100
150 120
*/
Sunday, January 10, 2021
Final Map Associative Container Program
/* Final Map Associative Container Program */
#include <iostream>
#include <map>
#include <string>
#include <utility>
using namespace std;
int main()
{
typedef map<string, int>mapType;
mapType populationMap;
int i;
int num;
string sname;
int popnum;
cout<<"How many states you want to enter in a Map"<<endl;
cin>>num;
for(i=0;i<num;i++)
{
cout<<"Enter State name"<<endl;
cin>>sname;
cout<<"Enter Population"<<endl;
cin>>popnum;
cout<<"***********************************************************************************"<<endl;
populationMap.insert(pair<string, int>(sname, popnum));
}
mapType::iterator iter = --populationMap.end();
// output the size of the map
cout<< "Size of populationMap: " <<populationMap.size() << '\n';
for (iter = populationMap.begin(); iter != populationMap.end(); ++iter) {
cout<<iter->first <<": " <<iter->second << " million\n";
cout<<"***********************************************************************************"<<endl;
}
// find will return an iterator to the matching element if it is found
// or to the end of the map if the key is not found
string state;
cout<<"Enter the name of the state to be find in Map"<<endl;
cin>>state;
//string country("Indonesia");
iter = populationMap.find(state);
if( iter != populationMap.end() )
cout<< state <<"'s populations is "
<<iter->second << " million\n";
else
cout<< "Key is not in populationMap" << '\n';
// clear the entries in the map
populationMap.clear();
}
Write C++ program using STL for sorting and searching user defined records such as Item records (Item code, name, cost, quantity etc) using vector container.
/* Write C++ program using STL for sorting and searching user defined records such as Item
records (Item code, name, cost, quantity etc) using vector container. */
#include <iostream> //standard input output stream header file
#include <algorithm> //The STL algorithms are generic because they can operate on a variety of data structures
#include <vector> //The header file for the STL vector library is vector.
using namespace std;
class Item
{
public:
char name[10];
int quantity;
int cost;
int code;
// operator overloading require here to search() // search code
bool operator==(const Item& i1) //Boolean operators allow you to create more complex conditional statements
{
if(code==i1.code) //operator will return 1 if the comparison is true, or 0 if he comparison is false
return 1;
return 0;
}
bool operator<(const Item& i1)
{
if(code<i1.code) //operator will return 1 if the comparison is true, or 0 if the comparison is false
return 1;
return 0;
}
};
vector<Item> o1; //declaring vector o1 for class item we create vector o1
void print(Item &i1);
void display();
void insert();
void search();
void dlt();
bool compare(const Item &i1, const Item &i2)
{
//if (i1.name != i2.name) return i1.cost < i2.cost;
return i1.cost < i2.cost; // sorting on cost
}
int main()
{
int ch;
do
{
cout<<"\n***** Menu *****";
cout<<"\n1.Insert";
cout<<"\n2.Display";
cout<<"\n3.Search";
cout<<"\n4.Sort";
cout<<"\n5.Delete";
cout<<"\n6.Exit";
cout<<"\nEnter your choice:";
cin>>ch;
switch(ch)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:
sort(o1.begin(),o1.end(),compare); //sort() function sorts the vector element in ascending order.
cout<<"\n\n Sorted on Cost";
display();
break;
case 5:
dlt();
break;
case 6:
exit(0);
}
}while(ch!=7);
return 0;
}
void insert()
{
Item i1;
cout<<"\nEnter Item Name:";
cin>>i1.name;
cout<<"\nEnter Item Quantity:";
cin>>i1.quantity;
cout<<"\nEnter Item Cost:";
cin>>i1.cost;
cout<<"\nEnter Item Code:";
cin>>i1.code;
o1.push_back(i1); // add elements to the end of vector by using push_back function//push_back fun supported by vector
}
void display()
{ //for each loop accepts a function which executes over each of the container elements. This loop is defined in the header file “algorithm”,
for_each(o1.begin(),o1.end(),print); // Execute print function from start to end of vector o1
}
void print(Item &i1)
{
cout<<"\n";
cout<<"\nItem Name:"<<i1.name;
cout<<"\nItem Quantity:"<<i1.quantity;
cout<<"\nItem Cost:"<<i1.cost;
cout<<"\nItem Code:"<<i1.code;
}
void search()
{
vector<Item>::iterator p; //Iterators are used to point at the memory addresses of STL containers
Item i1;
cout<<"\n Enter Item Code to search:";
cin>>i1.code;
p=find(o1.begin(),o1.end(),i1); //in-built function find
if(p==o1.end())
{
cout<<"\nNot found.";
}
else
{
cout<<"\nFound.";
}
}
void dlt()
{
vector<Item>::iterator p;
Item i1;
cout<<"\nEnter Item Code to delete:";
cin>>i1.code;
p=find(o1.begin(),o1.end(),i1);
if(p==o1.end())
{
cout<<"\nNot found.";
}
else
{
o1.erase(p);
cout<<"\nDeleted.";
}
}
Write a function template for selection sort that inputs, sorts and outputs an integer array and a float array
/* Write a function template for selection sort that inputs, sorts and outputs an integer array and a float array*/
#include<iostream>
using namespace std;
template<class T> //Function Template Declaration // T is a template argument that accepts different data types (int, float)
T selection_sort() //Template function
{
T a[5];
T temp;
for(int i=0;i<5;i++) //Accepting elements
{
cout<<"a["<<i<<"]=";
cin>>a[i];
}
for(int i=0;i<5;i++) //Sorting logic
{
for(int j=i+1;j<5;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
cout<<"Elements after sorting:\n"; //printing elements after sorting
for(int i=0;i<5;i++)
{
cout<<a[i]<<"\n";
}
} // Ending of function template
int main()
{
cout<<"Enter Integer elements for sorting...\n";
selection_sort<int>();
cout<<"Enter Floating elements for sorting...\n";
selection_sort<float>();
}
C++ program to write and read text in/from file.
//C++ program to write and read text in/from file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file; //object of fstream class
//opening file "sample.txt" in out(write) mode
file.open("shri.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}
cout<<"File created successfully."<<endl;
//write text into file
file<<"Welcome to Matoshri Engineering college, Nashik";
//closing the file
file.close();
//again open file in read mode
file.open("shri.txt",ios::in);
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}
//read untill end of file is not found.
char ch; //to read single character
cout<<"File content: ";
while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}
file.close(); //close file
return 0;
}
Implement a class Complex which represents the Complex Number data type. Implement the following operations: 1. Constructor (including a default constructor which creates the complex number 0+0i). 2. Overloaded operator+ to add two complex numbers. 3. Overloaded operator* to multiply two complex numbers. 4. Overloaded << and >> to print and read Complex Numbers.
/*Implement a class Complex which represents the Complex Number data type.
Implement the following operations:
1. Constructor (including a default constructor which creates the complex number 0+0i).
2. Overloaded operator+ to add two complex numbers.
3. Overloaded operator* to multiply two complex numbers.
4. Overloaded << and >> to print and read Complex Numbers. */
#include<iostream>
using namespace std;
class complex
{
public:
float real,img;
complex() // default constructor
{
real=0;
img=0;
}
complex operator +(complex); // declaration for addition
complex operator *(complex); // declaration for multiplication
friend ostream &operator<<(ostream&,complex&); // output function//<< operator return obj of ostream class//given ostream class as a return type
friend istream &operator>>(istream&,complex&); // input function
};
// operator overloading syntax
complex complex::operator +(complex obj) /* This is automatically called when '+' is used with between two Complex objects */
{
complex temp;
temp.real=real+obj.real;
temp.img=img+obj.img;
return (temp);
}
complex complex::operator *(complex obj)
{
complex temp;
temp.real=(real*obj.real)-(img*obj.img);
temp.img=(real*obj.img)+(img+obj.img);
return (temp);
}
istream &operator>>(istream& is,complex& obj) //defining (extraction)>> operator
{
is>>obj.real; //accepting real part with object of istream class
is>>obj.img; //accepting imaginary part with object of istream class
return is;
}
ostream &operator<<(ostream& os,complex& obj) //defining <<(insertion) operator
{
os<<obj.real; //displaying real part with object of ostream class
os<<"+"<<obj.img<<"i"; //displaying imaginary part with object of ostream class
return os;
}
int main()
{
complex a,b,c,d;
//Enter first complex number";
cout<<"\n Enter real and imaginary part of first complex number:";
cin>>a;
// Enter second complex number";
cout<<"\n Enter real and imaginary part of second complex number:";
cin>>b;
cout<<"\nArithmetic operations are :";
c=a+b;
cout<<"\n Addition is:"<<c;
d=a*b;
cout<<"\n Multiplication is:"<<d<<"\n";
return 0;
}
/*output-
Enter real and imaginary part of first complex number:
5 6
Enter real and imaginary part of second complex number:
2 3
Arithmetic operations are :
Addition is:7+9i
Multiplication is:-8+24i
*/
Develop a program in C++ to create a database of student’s information system containing the following information: Name, Roll number, Class, Division, Date of Birth, Blood group, Contact address, Telephone number, Driving license no. and other. Construct the database with suitable member functions. Make use of constructor, default constructor, copy constructor, destructor, static member functions, friend class, this pointer, inline code and dynamic memory allocation operators-new and delete
/* Problem Statement : Develop a program in C++ to create a database of student’s information system containing the following information: Name, Roll number, Class, Division, Date of Birth, Blood group, Contact address, Telephone number, Driving license no. and other. Construct the database with suitable member functions. Make use of constructor, default constructor, copy constructor, destructor, static member functions, friend class, this pointer, inline code and dynamic memory allocation operators-new and delete*/
Algorithm
1. Start
2. Read personnel information such as Name, Date of Birth, Blood group, Height, Weight, Insurance Policy number, Contact address, telephone number, driving license no.
3. Print all information from the database.
4.stop
Input : Personnel information such as Name, Date of Birth, Blood group, Height, Weight, Insurance Policy number, contact address, telephone number, driving license no.
Output: Display personal information from database.
#include<iostream>
#include<string.h> // header file declares a set of functions to work strings.
using namespace std;
class db
{
int roll;
char name[20];
char Class[10];
char Div[10];
char dob[12];
char bg[5],city[10];
char phone[12],license[12];
public:
static int stdno; // declaration of static variable
static void count() // defination of static function
{
cout<<"\n No.of objects created: "<<stdno;
}
db() // default constructor
{
roll=7;
strcpy(name,"Sachin");
strcpy(Class,"SE");
strcpy(Div,"A");
strcpy(dob,"13/08/1992");
strcpy(bg,"B+");
strcpy(city,"Pune");
strcpy(phone,"9123456789");
strcpy(license,"A1010");
++stdno;
}
void getdata()// defining member function
{
cout<<"\n\nEnter:name,roll,Class,Div,Dob,bg,city,phone,license \n\n";
cin>>name>>roll>>Class>>Div>>dob>>bg>>city>>phone>>license;
}
friend void display(db d); // declaration of friend function
~db() // destructor
{
cout<<"\n\n"<<this->name<<"(Object) is destroyed!\n";
}
};
void display(db d) // defination of friend function
{
cout<<"\n Name:"<<d.name;
cout<<"\n Roll_No:"<<d.roll;
cout<<"\n Class:"<<d.Class;
cout<<"\n Div:"<<d.Div;
cout<<"\n DOB:"<<d.dob;
cout<<"\n Blood group:"<<d.bg;
cout<<"\n City:"<<d.city;
cout<<"\n Phone_No:"<<d.phone;
cout<<" \n Liacense_No:"<<d.license;
}
int db::stdno; // Define static data member stdno outside the class;
int main()
{
int n,i;
db d1,*ptr[5];
cout<<"\nDefault values:";
display(d1);
d1.getdata();
display(d1);
cout<<"\nHow many objects u want to create?:";
cin>>n;
for(i=0;i<n;i++)
{
ptr[i]=new db(); //new operator use to dynamic memory(run time) allocation
ptr[i]->getdata();
}
cout<<"\n"<<"name"<<"roll"<<"Class"<<"Div"<<"dob"<<"bg"<<"contact"<<"phone"<<"license";
for(i=0;i<n;i++)
display(*ptr[i]);
db::count(); // calling of static function
for(i=0;i<n;i++)
{
delete(ptr[i]); //delete operator use to deallocation of memory
}
cout<<"\nObjects deleted!" ;
}
Imagine a publishing company which does marketing for book and audio cassette versions. Create a class publication that stores the title (a string) and price (type float) of publications. From this class derive two classes: book which adds a page count (type int) and tape which adds a playing time in minutes (type float). Write a program that instantiates the book and tape class, allows user to enter data and displays the data members.
/* Imagine a publishing company which does marketing for book and audio cassette versions. Create a class publication that stores the title (a string) and price (type float) of publications.
From this class derive two classes: book which adds a page count (type int) and tape which adds a playing time in minutes (type float). Write a program that instantiates the book and tape class, allows user to enter data and displays the data members. */
Algorithm:
Step 1: Start the program
Step 2: Create a base class publication.
Step 3: Declare title and price data members as protected members.
Step 4: Define a default and parameterised constructor in a base class to initialize data members(i.e title and price) Step 5: Create a derived class book which has pagecount data member.
Step 6: Define a constructor of book class which has 3 parameters from which 2 are used to initialize data members of base class and one for its own.
Step 7:Define a display function to display a members of book (title and price inherited from base class publication and pagecount(its own))
Step 8: Follow the same steps for CD class
#include <iostream>
#include<string>
using namespace std;
class publication
{
protected:
string title;
float price;
public:
publication()
{
price=0.0;
title=" ";
}
publication(string t,float p)
{
title=t;
price=p;
}
};
class book : public publication
{
int pagecount;
public:
book()
{
pagecount=0;
}
book(string t,float p, int pc):publication(t,p)
{
pagecount=pc;
}
void display()
{
cout<<"title :"<<title<<endl;
cout<<"Price: "<<price<<endl;
cout<<"Pagecount :"<<pagecount<<endl;
} };
class CD : public publication
{
float time;
public:
CD()
{
time=0.0;
}
CD(string t,float p,float tim):publication(t,p)
{
time=tim;
}
void display()
{
cout<<"title :"<<title<<endl;
cout<<"Price: "<<price<<endl;
cout<<"time in minutes :"<<time<<endl;
}
};
int main()
{
cout<<endl<<"Book data"<<endl;
book b("C++",230,500);
b.display();
cout<<endl<<"CD Data"<<endl;
CD c("programming",50,120.5);
c.display();
return 0;
}