This chapter from Jalote gives us insight into the object oriented design and analysis.
The OO concepts which are learned from C++ point of view, will be much more clear and their applications in real world projects and thier relevancy will be clear too.
Thursday, April 15, 2010
Object Oriented Design
OOP Variations
2. Write a C++ program to find the factorial of a given number using Function
3. Write a C++ program using SWITCH CASE structure to display the given number in words. (enter number between 1 and 9).
4. Write a C++ program to check whether the given string is palindrome or not
5. Write a C++ program to find the number of Odd and Even numbers in a given array.
6. Write a C++ program to transpose a 3x3 matrix.
7. Write a C++ program to add two 3x3 matrices
8. Write a C++ program using function to determine whether the given number is prime or not
9. Write a C++ program to define a class employee with the following specification
private members of class employee
empno – integer
ename - 20 characters
basic – float
Netpay, hra, da, float
calculate() - A function to find the basic+da+hra with float return type
public member functions
havedata() - A function to accept values for empno, ename, basic,hra,da and call
calculate() to compute netpay
dispdata() - A function to display all the data members on the screen
10. Write a C++ program that uses function overloading to do the following tasks
a) find the maximum of two numbers (integers)
b) find the maximum of three numbers (integers)
11. Write a C++ program to find the sum and difference of two numbers using inheritance
ADD SUBTRACT
public add(), accept(), plus() subtract(), minus()
private sum() sub()
protected num1, num2
12. Write a C++ program to get the following output
C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
13. Animal insurance
Write a program that prints the insurance fee to pay for a pet according to the following rules:
• A dog that has been neutered costs $50.
• A dog that has not been neutered costs $80.
• A cat that has been neutered costs $40.
• A cat that has not been neutered costs $60.
• A bird or reptile costs nothing.
• Any other animal generates an error message.
The program should prompt the user for the appropriate information, using a code to determine the kind of animal (i.e. D or d represents a dog, C or c represents a cat, B or b represents a bird, R or r represents a reptile, and anything else represents some other kind of animal).
After printing the insurance fee, the program should ask the user if (s)he wants to insure another animal.
Remember to write the program in a clear style with indentation.
14. Pupils' heights
The health visitor at a school is going to measure the heights of all pupils. For each class she makes a statistics giving the number of pupils of each height and the average height.
Make a C++ program that helps the health visitor making the statistics.
Example:
In a class with 20 pupils the heights of the individual pupils, in centimeters, are:
175, 167, 160, 164, 183, 187, 188, 179, 176, 175,
169, 175, 176, 178, 165, 160, 173, 165, 187, 178
The program should read in all the numbers and make a table like this:
height number of pupils
160 2
164 1
165 2
167 1
... ...
... ...
188 1
average height 174.0
15. Pocket calculator
The program should read in a text string containing a list of numbers separated by + or - and output the sum. The program should also tell how many positive numbers and how many negative (subtracted) numbers there are.
Example:
input: 8.4 + 2.6 - 3.5 + 1
output: result = 8.5, positive numbers: 3, negative numbers: 1.
The input cannot contain any other operators than + and -. Spaces are allowed.
The program should be organized so that main reads the input as a single text string and outputs the results. The interpretation of the text string and calculation of results should be in a separate sub-function. Do not use global variables.
Tip: the function atof can read a number from a text string. Anything that comes after the number is ignored by atof.
16. The political oracle
In the year 2097, the president of the United States of Europe doesn't have the time to write his own political speeches because he is busy hosting a lottery show on TV. His secretary has asked you to make a computer program which can write political speeches by combining popular clichés randomly. A statement is generated by combining randomly selected phrases from each of the categories G, A, S, and V below according to the scheme G - A - S - V - G - A - S. For example:
"My improved freedom benefits our common responsible national security."
Hint: The function random(n) will give you a random number in the interval from 0 to n-1. Use this function to choose a cliché from a category containing n clichés. The function randomize() must be called in the start of the main program before the first call to random(n).
Write #include
Category G
my, our common, the party's, my family's, our children's, my fellow Europeans', the government's, the industry's, the consumers', the immigrants', the only truly
Category A
improved, responsible, peacekeeping, free, pro-life, politically correct, integrated, federal, progressive, anti-crime, drug-addicted, gradual, democratic, genetically engineered, racial
Category S
freedom, national security, abuse, opportunity, tax cut, congress, task force, Europe, decision, dialogue, future, community, answer, environment, set of family-values, legislation, discrimination
Category V
benefits, improves, decreases, supports, is built on, is the best guarantee for, creates an opportunity for, forms, is necessary for, will be established to combat
17. Matrix operations
Write a program that can do the following:
• addition of two matrices
• subtraction of two matrices
• multiplication of a matrix by a scalar
• multiplication of a matrix by a matrix
• transpose a matrix
The order of the matrices could be 3 x 3, or variable if you want.
Equations
18. Make a function that can solve two linear equations with two unknowns. The solution should be returned through pointer parameters or reference parameters. Make a program that inputs the six coefficients, calls the function, and outputs the solution.
19. Make a function that solves a quadratic equation, and a program that uses this function. The function should return the number of solutions as well as the solutions (if any) to the calling program.
In case you've forgotten everything you've learned in math, here are the formulae:
Discriminant
20. Bit manipulation
Write a function that prints out an integer in binary representation.
Write a function that finds the parity of an integer. The parity is 1 if there is an odd number of 1-bits in the binary representation of the integer, and 0 if there is an even number of 1-bits.
Write a program that reads in an integer and outputs the number in binary representation and the parity of the number, using the functions above.
21. Primes
A prime number is a positive integer which is not divisible by any other number, except by 1. The first ten prime numbers are:
1, 2, 3, 5, 7, 11, 13, 17, 19, 23, ...
Write a program that finds all prime numbers below 1000.
The program should determine if a number is prime by trying if it is divisible by any of the prime numbers found so far. If it is not divisible by any prime number, then it is a prime. There is no need to test even numbers.
22. Telephone directory
Make a program that can sort a list of names and telephone numbers alphabetically. Persons are sorted alphabetically by their last names. Persons with the same last name are sorted by their first names.
Input: names and telephone numbers,
Output: list of names and telephone numbers ordered alphabetically.
Define a structure named person that contains a person's first name, last name, and telephone number.
Define a function that compares two structures of type person according to the following prototype:
int compare(person * a, person * b);
This function should return a negative value if person a comes before b, and a positive value if b comes before a. (You may use the function stricmp(name1,name2) to compare two strings).
Define a function that swaps the contents of two structures of type person:
void swap(person * x, person * y);
Use the following function to sort an array of structures of type person:
void sort(person * list, int NumberOfPersons)
{ // sort list using bubble sort method (page 96):
int a, b;
for (a=1; a
{
for (b=NumberOfPersons-1; b>=a; b--)
{
if (compare(list+b-1, list+b) > 0)
{
swap(list+b-1, list+b);
}
}
}
}
23. Ohm's law
Make a class describing a resistor with the following members:
• a private data member for the resistance, R
• a public member function to set the value of R
• a public member function to calculate the current I from the voltage E
• a public member function to calculate the voltage E from the current I
• a public member function to calculate the power dissipation P from the current I using the formula P = I•E, where E is calculated using the previous member function.
Make a program to test this class.
24. Pendulum
Make a C++ class describing a simple pendulum with appropriate data members and member functions for setting the values of the length , mass m, and energy E, calculating the time period
and the velocity in the lower position
.
25. Parabola as object
Make a class defining a polynomial of second degree y = A x2 + B x + C
The coefficients A, B, C should be private. The class should contain the following member functions:
• a function that sets the coefficients to desired values
• a function that calculates y for a given value of x
• a function that tells how many roots there are and returns the roots (if any)
• a function that tells whether the polynomial has a maximum, a minimum, or no extremum, and gives x and y for the extremum (if any)
Make a program to test an object of this class.
In case you've forgotten everything you've learned in math, here are the formulae:
Discriminant
Wednesday, March 31, 2010
Complex Number Class
A complex number is a number that has two components; the real component and the imaginary component.
a + bi
Arithmetic is defined as follows:
(a + bi) + (c + di) = (a + c) + (b + d)i
(a + bi) - (c + di) = (a - c) + (b - d)i
(a + bi) * (c + di) = (ac - bd) + (ad + bc)i
(a + bi) / (c + di) = (ac + bd) / (c**2+d**2) + [ (bc -ad) /(c**2+d**2)]i
Class Declaration
class complex
{
public:
complex();
complex(double,double);
double getReal() const;
void setReal(double);
complex operator+(complex) const;
complex operator-(complex) const;
complex operator*(complex) const;
complex operator/(complex) const;
private:
double real, imag;
};
complex::complex():real(0),y(0)
{ //default constructor
}
complex :: complex(double r, double im)
{
real = r;
imag = im;
}
complex complex::operator+(complex c) const
{
complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
complex complex::operator/(complex c) const
{
complex temp;
temp.real = (real*c.real + imag*c.imag)/
( pow(c.real,2) + pow(imag,2) );
temp.imag = (imag*c.real - real*c.imag)/
( pow(c.real,2) + pow(imag,2) );
return temp;
}
complex complex::operator*(complex c) const
{
complex temp;
temp.real = real*c.real – imag*c.imag;
temp.imag = real*c.imag + imag*c.real;
return temp;
}
Tuesday, March 30, 2010
Scan line poly fill
#include
#include
main()
{
int n,i,j,k,gd,gm,dy,dx;
int x,y,temp;
int a[20][2],xi[20];
float slope[20];
clrscr();
printf("\n\n\tEnter the no. of edges of polygon : ");
scanf("%d",&n);
printf("\n\n\tEnter the cordinates of polygon :\n\n\n ");
for(i=0;i
{
printf("\tX%d Y%d : ",i,i);
scanf("%d %d",&a[i][0],&a[i][1]);
}
a[n][0]=a[0][0]; // polygon
a[n][1]=a[0][1];
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\bgi");
/*- draw polygon -*/
for(i=0;i
{
line(a[i][0],a[i][1],a[i+1][0],a[i+1][1]);
}
getch();
for(i=0;i
{
dy=a[i+1][1]-a[i][1];
dx=a[i+1][0]-a[i][0];
if(dy==0) slope[i]=1.0;
if(dx==0) slope[i]=0.0;
if((dy!=0)&&(dx!=0)) /*- calculate inverse slope -*/
{
slope[i]=(float) dx/dy;
}
}
for(y=0;y< 480;y++) // find x intersections
{
k =0;
for(i=0;i
{
if( ((a[i][1]<=y)&&(a[i+1][1]>y))
((a[i][1]>y)&&(a[i+1][1]<=y)))
{
xi[k]=(int)(a[i][0]+slope[i]*(y-a[i][1]));
k++;
}
}
for(j=0;j
for(i=0;i
{
if(xi[i]>xi[i+1])
{
temp=xi[i];
xi[i]=xi[i+1];
xi[i+1]=temp;
}
}
setcolor(35);
for(i=0;i
{
line(xi[i],y,xi[i+1]+1,y);
getch();
}
}
return 0;
}
FTP access
This is very serious!!!
Definately some one from your class....
Tuesday, March 16, 2010
Practical Examination tips
2. All Graphics program must work in k/b mode as well as mouse interfacing mode
3. As far as possible try using function and operator overloading for all classes
4. << and >> needs to be overloaded for classes for input and output
5. Using formatted IO from iostream and iomanip is compulsory
6. Try other possible variation in problem statement
Start practicing now, so that you will be comfortable with all the c++ constructs.
Friday, February 26, 2010
The Sutherland-Hodgeman Polygon Clipping Algorithm
1. Introduction
It is often necessary, particularly in graphics applications, to "clip" a given polygon with another. Figure 1 shows an example. In this article we'll look at the particular case where the clipping polygon is a rectangle which is oriented parallel with the axes. For this case, the Sutherland-Hodgeman algorithm is often employed. This is the algorithm that we will explore.
Figure 1
2. The Sutherland-Hodgeman Algorithm
The Sutherland-Hodgeman polygon clipping algorithm is relatively straightforward and is easily implemented in C. It does have some limitations, which we'll explore later. First, let's see how it works.
For each of the four sides of the clipping rectangle, consider the line L through the two points which define that side. For each side, this line creates two planes, one which includes the clipping rectangle and one which does not. We'll call the one which does not the "clipping plane" (Figure 2).
L
Figure 2
For each of the four clipping planes, we must remove any vertices of the clipped polygon which lie inside the plane and create new points where the segments associated with these vertices cross the line L (Figure 3).
L
Figure 3
After clipping each of the four planes, we are left with the clipped polygon.
3. Limitations
This algorithm always produces a single output polygon, even if the clipped polygon is concave and arranged in such a way that multiple output polygons might reasonably be expected. Instead, the polygons will be linked with overlapping segments along the edge of the clipping rectangle (Figure 4). This may or may not be the desired result, depending on your application.
Figure 4
4. Practical Implementation
#include <math.h>
#include <assert.h>
#define CP_MAXVERT 32
#define CP_LEFT 0
#define CP_RIGHT 1
#define CP_TOP 2
#define CP_BOTTOM 3
struct rect{
double t; /* Top */ double b; /* Bottom */ double l; /* Left */ double r; /* Right */
};
struct point{ double x; double y;
};
To determine the correct course of action in the main algorithm, we'll need to be able to check if a given point is "inside" or "outside". In this sense, we take "outside" to mean "within the clipping plane". This function takes the point in question, the clipping rectangle, and a number indicating which side of the rectangle is forming the clipping plane.
int cp_inside( struct point p, struct rect r, int side )
{
switch( side ){
case CP_LEFT:
return p.x >= r.l;
case CP_RIGHT:
return p.x <= r.r;
case CP_TOP:
return p.y <= r.t;
case CP_BOTTOM:
return p.y >= r.b;
}
}
When one of the two points defi ning a line segment is "inside" and the other is "outside", we will need to create a new vertex where the segment intersects the clipping rectangle.
This function takes the "inside" point (p), the "outside" point (q), the clipping rectangle, and again the side in question.
It first finds the slope (a) and y-intercept (b) of the line segment pq. Now, depending on the side under consideration, either the x or y component of the new point is set equal to that of the bounding side and the remaining component is computed using the slope and intercept previously found. When considering the top or bottom sides, it is possible that the segment pq is vertical. This condition can be recognized when the slope (a) is infinite. In this special case, the x component of the new point will be the same as the x component of
p or q.
struct point cp_intersect( struct point p, struct point q, struct rect r, int side )
{
struct point t;
double a, b;
/* fi nd slope and intercept of segment pq */
a = ( q.y - p.y ) / ( q.x - p.x );
b = p.y - p.x * a;
switch( side ){
case CP_LEFT:
t.x = r.l;
t.y = t.x * a + b;
break;
case CP_RIGHT:
t.x = r.r;
t.y = t.x * a + b;
break;
case CP_TOP:
t.y = r.t;
if( isfi nite(a) )
t.x = ( t.y - b ) / a;
else
break;
t.x = p.x;
case CP_BOTTOM:
t.y = r.b;
if( isfi nite(a) )
t.x = ( t.y - b ) / a;
else
}
return t;
}
break;
t.x = p.x;
This function clips the clipped polygon against the clipping plane for a particular side of the clipping rectangle. Starting with the fi rst vertex in the clipped polygon, we consider each vertex (p) along with the one before it (s).
There are four ways that these two points may be arranged:
Both s and p are "inside": The point p should be included in the output polygon.
The point s is "outside" while p is "inside": The intersection of sp and the line L defi ning the clip- ping plane should be included in the output, followed by p.
The point s is "inside" while p is "outside": The intersection of sp and the line L defi ning the clip- ping plane should be included in the output.
The points s and p are both "outside": nothing need be done on this step.
void cp_clipplane( int *v, struct point in[CP_MAXVERT], struct rect r, int side )
{
int i, j=0;
struct point s, p;
struct point out[CP_MAXVERT];
s = in[*v-1];
for( i = 0 ; i < *v ; i++ ){
p = in[i];
if( cp_inside( p, r, side ) ){
/* point p is "inside" */
if( !cp_inside( s, r, side ) ){
/* p is "inside" and s is "outside" */ out[j] = cp_intersect( p, s, r, side ); j++;
}
out[j] = p; j++;
}else if( cp_inside( s, r, side ) ){
/* s is "inside" and p is "outside" */ out[j] = cp_intersect( s, p, r, side ); j++;
}
s = p;
}
/* set return values */
*v = j;
for( i = 0 ; i < *v ; i++ ){
in[i] = out[i];
}
}
The actual clippoly function is very simple; it calls the previous function (cp_clipplane) once for each side of the clipping rectangle. First, though, it performs a few tests to make sure that the input data make sense and that there will be room to store the output polygon.
void clippoly( int *v, struct point p[CP_MAXVERT], struct rect r )
{
/* sanity checks */
assert( *v <= CP_MAXVERT / 2 );
assert( r.l < r.r );
assert( r.b < r.t );
cp_clipplane( v, p, r, CP_LEFT ); cp_clipplane( v, p, r, CP_RIGHT ); cp_clipplane( v, p, r, CP_TOP ); cp_clipplane( v, p, r, CP_BOTTOM );
}
From : http://www.aftermath.net/