1: #include <iostream.h>
2:
3: int main()
4: {
5: cout << "I love C++\n";
6: return 0;
7: }
int main(){}
1: #include <iostream.h>
2: main()
3: {
4: cout << Is there a bug here?";
5: }
1: #include <iostream.h>
2: main()
3: {
4: cout << "Is there a bug here?";
5: }
enum COLOR { WHITE, BLACK = 100, RED, BLUE, GREEN = 300 };
BLUE = 102
const float PI = 3.14159;
float myPi = PI;
myAge = 39; a = myAge++; b = ++myAge; myAge: 41, a: 39, b: 41
14
7. What is the difference between if(x = 3) and if(x == 3)?
The first one assigns 3 to x and returns true. The second one tests
whether x is equal to 3; it returns true if the value of x
is equal to 3 and false if it is not.
8. Do the following values evaluate to TRUE or FALSE?
if (x > y)
x = y;
else // y > x || y == x
y = x;
1: #include <iostream.h>
2: int main()
3: {
4: int a, b, c;
5: cout << "Please enter three numbers\n";
6: cout << "a: ";
7: cin >> a;
8: cout << "\nb: ";
9: cin >> b;
10: cout << "\nc: ";
11: cin >> c;
12:
13: if (c = (a-b))
14 {
15: cout << "a: " << a << " minus b: ";
16: cout << b << " _equals c: " << c;
17: }
15: else
16: cout << "a-b does not equal c: ";
17: return 0;
18: }
1: #include <iostream.h>
2: int main()
3: {
4: int a = 2, b = 2, c;
5: if (c = (a-b))
6: cout << "The value of c is: " << c;
7: return 0;
8: }
unsigned long int Perimeter(unsigned short int length, unsigned short int width)
{
return 2*length + 2*width;
}
#include <iostream.h>
void myFunc(unsigned short int x);
int main()
{
unsigned short int x, y;
y = myFunc(int);
cout << "x: " << x << " y: " << y << "\n";
return 0;
}
void myFunc(unsigned short int x)
{
return (4*x);
}
#include <iostream.h>
int myFunc(unsigned short int x);
int main()
{
unsigned short int x, y;
y = myFunc(int);
cout << "x: " << x << " y: " << y << "\n";
return 0;
}
int myFunc(unsigned short int x)
{
return (4*x);
}
{
if (valTwo == 0)
return -1;
else
return valOne / valTwo;
}
#include <iostream.h>
typedef unsigned short int USHORT;
typedef unsigned long int ULONG;
short int Divider(
unsigned short int valone,
unsigned short int valtwo);
int main()
{
USHORT one, two;
short int answer;
cout << "Enter two numbers.\n Number one: ";
cin >> one;
cout << "Number two: ";
cin >> two;
answer = Divider(one, two);
if (answer > -1)
cout << "Answer: " << answer;
else
cout << "Error, can't divide by zero!";
return 0;
}
#include <iostream.h>
typedef unsigned short USHORT;
typedef unsigned long ULONG;
ULONG GetPower(USHORT n, USHORT power);
int main()
{
USHORT number, power;
ULONG answer;
cout << "Enter a number: ";
cin >> number;
cout << "To what power? ";
cin >> power;
answer = GetPower(number,power);
cout << number << " to the " << power << "th power is " <<
answer << endl;
return 0;
}
ULONG GetPower(USHORT n, USHORT power)
{
if(power == 1)
return n;
else
return (n * GetPower(n,power-1));
}
void Cat::Meow()
class Employee
{
int Age;
int YearsOfService;
int Salary;
};
class Employee
{
public:
int GetAge() const;
void SetAge(int age);
int GetYearsOfService()const;
void SetYearsOfService(int years);
int GetSalary()const;
void SetSalary(int salary);
private:
int Age;
int YearsOfService;
int Salary;
};
main()
{
Employee John;
Employee Sally;
John.SetAge(30);
John.SetYearsOfService(5);
John.SetSalary(50000);
Sally.SetAge(32);
Sally.SetYearsOfService(8);
Sally.SetSalary(40000);
cout << "At AcmeSexist company, John and Sally have the same
job.\n";
cout << "John is " << John.GetAge() << " years old and he has
been with";
cout << "the firm for " << John.GetYearsOfService << "
years.\n";
cout << "John earns $" << John.GetSalary << " dollars per
year.\n\n";
cout << "Sally, on the other hand is " << Sally.GetAge() << "
years old and has";
cout << "been with the company " << Sally.GetYearsOfService;
cout << " years. Yet Sally only makes $" << Sally.GetSalary();
cout << " dollars per year! Something here is unfair.";
float Employee:GetRoundedThousands()const
{
return Salary / 1000;
}
class Employee
{
public:
Employee(int age, int yearsOfService, int salary);
int GetAge()const;
void SetAge(int age);
int GetYearsOfService()const;
void SetYearsOfService(int years);
int GetSalary()const;
void SetSalary(int salary);
private:
int Age;
int YearsOfService;
int Salary;
};
class Square
{
public:
int Side;
}
class Cat
{
int GetAge()const;
private:
int itsAge;
};
class TV
{
public:
void SetStation(int Station);
int GetStation() const;
private:
int itsStation;
};
main()
{
TV myTV;
myTV.itsStation = 9;
TV.SetStation(10);
TV myOtherTv(2);
}
for (x = 0, y = 10; x < 100; x++, y++)
for (int x = 100; x < 100; x++)
for(;;)
{
// This for loop never ends!
}
while(1)
{
// This while loop never ends!
}
for (int x = 0; x < 100; x++) 100
for (int i = 0; i< 10; i++)
{
for ( int j = 0; j< 10; j++)
cout << "0";
cout << "\n";
}
for (int x = 100; x<=200; x+=2)
int x = 100;
while (x <= 200)
x+= 2;
int x = 100;
do
{
x+=2;
} while (x <= 200);
int counter = 0
while (counter < 10)
{
cout << "counter: " << counter;
counter++;
}
for (int counter = 0; counter < 10; counter++);
cout << counter << "\n";
int counter = 100;
while (counter < 10)
{
cout << "counter now: " << counter;
counter--;
}
cout << "Enter a number between 0 and 5: ";
cin >> theNumber;
switch (theNumber)
{
case 0:
doZero();
case 1: // fall through
case 2: // fall through
case 3: // fall through
case 4: // fall through
case 5:
doOneToFive();
break;
default:
doDefault();
break;
}
unsigned short *pAge = &yourAge;
*pAge = 50;
int theInteger; int *pInteger = &theInteger; *pInteger = 5;
#include <iostream.h>
int main()
{
int *pInt;
*pInt = 9;
cout << "The value at pInt: " << *pInt;
return 0;
}
int main()
{
int SomeVariable = 5;
cout << "SomeVariable: " << SomeVariable << "\n";
int *pVar = & SomeVariable;
pVar = 9;
cout << "SomeVariable: " << *pVar << "\n";
return 0;
}
int main()
{
int varOne;
int& rVar = varOne;
int* pVar = &varOne;
rVar = 5;
*pVar = 7;
return 0;
}
int main()
{
int varOne;
const int * const pVar = &varOne;
*pVar = 7;
int varTwo;
pVar = &varTwo;
return 0;
}
int main()
{
int * pVar;
*pVar = 9;
return 0;
}
int main()
{
int VarOne;
int * pVar = &varOne;
*pVar = 9;
return 0;
}
int FuncOne();
int main()
{
int localVar = FunOne();
cout << "the value of localVar is: " << localVar;
return 0;
}
int FuncOne()
{
int * pVar = new int (5);
return *pVar;
}
void FuncOne();
int main()
{
FuncOne();
return 0;
}
void FuncOne()
{
int * pVar = new int (5);
cout << "the value of *pVar is: " << *pVar ;
}
1: #include <iostream.h>
2:
3: class CAT
4: {
5: public:
6: CAT(int age) { itsAge = age; }
7: ~CAT(){}
8: int GetAge() const { return itsAge;}
9: private:
10: int itsAge;
11: };
12:
13: CAT & MakeCat(int age);
14: int main()
15: {
16: int age = 7;
17: CAT Boots = MakeCat(age);
18: cout << "Boots is " << Boots.GetAge() << " years old\n";
19: return 0;
20: }
21:
22: CAT & MakeCat(int age)
23: {
24: CAT * pCat = new CAT(age);
25: return *pCat;
26: }
1: #include <iostream.h>
2:
3: class CAT
4: {
5: public:
6: CAT(int age) { itsAge = age; }
7: ~CAT(){}
8: int GetAge() const { return itsAge;}
9: private:
10: int itsAge;
11: };
12:
13: CAT * MakeCat(int age);
14: int main()
15: {
16: int age = 7;
17: CAT * Boots = MakeCat(age);
18: cout << "Boots is " << Boots->GetAge() << " years old\n";
19: delete Boots;
20: return 0;
21: }
22:
23: CAT * MakeCat(int age)
24: {
25: return new CAT(age);
26: }
class SimpleCircle
{
public:
SimpleCircle();
~SimpleCircle();
void SetRadius(int);
int GetRadius();
private:
int itsRadius;
};
SimpleCircle::SimpleCircle():
itsRadius(5)
{}
SimpleCircle::SimpleCircle(int radius):
itsRadius(radius)
{}
const SimpleCircle& SimpleCircle::operator++()
{
++(itsRadius);
return *this;
}
// Operator ++(int) postfix.
// Fetch then increment
const SimpleCircle SimpleCircle::operator++ (int)
{
// declare local SimpleCircle and initialize to value of *this
SimpleCircle temp(*this);
++(itsRadius);
return temp;
}
class SimpleCircle
{
public:
SimpleCircle();
SimpleCircle(int);
~SimpleCircle();
void SetRadius(int);
int GetRadius();
const SimpleCircle& operator++();
const SimpleCircle operator++(int);
private:
int *itsRadius;
};
SimpleCircle::SimpleCircle()
{itsRadius = new int(5);}
SimpleCircle::SimpleCircle(int radius)
{itsRadius = new int(radius);}
const SimpleCircle& SimpleCircle::operator++()
{
++(itsRadius);
return *this;
}
// Operator ++(int) postfix.
// Fetch then increment
const SimpleCircle SimpleCircle::operator++ (int)
{
// declare local SimpleCircle and initialize to value of *this
SimpleCircle temp(*this);
++(itsRadius);
return temp;
}
SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
int val = rhs.GetRadius();
itsRadius = new int(val);
}
SimpleCircle& SimpleCircle::operator=(const SimpleCircle & rhs)
{
if (this == &rhs)
return *this;
delete itsRadius;
itsRadius = new int;
*itsRadius = rhs.GetRadius();
return *this;
}
#include <iostream.h>
class SimpleCircle
{
public:
// constructors
SimpleCircle();
SimpleCircle(int);
SimpleCircle(const SimpleCircle &);
~SimpleCircle() {}
// accessor functions
void SetRadius(int);
int GetRadius()const;
// operators
const SimpleCircle& operator++();
const SimpleCircle operator++(int);
SimpleCircle& operator=(const SimpleCircle &);
private:
int *itsRadius;
};
SimpleCircle::SimpleCircle()
{itsRadius = new int(5);}
SimpleCircle::SimpleCircle(int radius)
{itsRadius = new int(radius);}
SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
int val = rhs.GetRadius();
itsRadius = new int(val);
}
SimpleCircle& SimpleCircle::operator=(const SimpleCircle & rhs)
{
if (this == &rhs)
return *this;
*itsRadius = rhs.GetRadius();
return *this;
}
const SimpleCircle& SimpleCircle::operator++()
{
++(itsRadius);
return *this;
}
// Operator ++(int) postfix.
// Fetch then increment
const SimpleCircle SimpleCircle::operator++ (int)
{
// declare local SimpleCircle and initialize to value of *this
SimpleCircle temp(*this);
++(itsRadius);
return temp;
}
int SimpleCircle::GetRadius() const
{
return *itsRadius;
}
int main()
{
SimpleCircle CircleOne, CircleTwo(9);
CircleOne++;
++CircleTwo;
cout << "CircleOne: " << CircleOne.GetRadius() << endl;
cout << "CircleTwo: " << CircleTwo.GetRadius() << endl;
CircleOne = CircleTwo;
cout << "CircleOne: " << CircleOne.GetRadius() << endl;
cout << "CircleTwo: " << CircleTwo.GetRadius() << endl;
return 0;
}
SQUARE SQUARE ::operator=(const SQUARE & rhs)
{
itsSide = new int;
*itsSide = rhs.GetSide();
return *this;
}
VeryShort VeryShort::operator+ (const VeryShort& rhs)
{
itsVal += rhs.GetItsVal();
return *this;
}
VeryShort VeryShort::operator+ (const VeryShort& rhs)
{
return VeryShort(itsVal + rhs.GetItsVal());
}
SomeArray[2][3][2] = { { {1,2},{3,4},{5,6} } , { {7,8},{9,10},{11,12} } };
int GameBoard[3][3];
int GameBoard[3][3] = { {0,0,0},{0,0,0},{0,0,0} }
class Node
{
public:
Node ();
Node (int);
~Node();
void SetNext(Node * node) { itsNext = node; }
Node * GetNext() const { return itsNext; }
int GetVal() const { return itsVal; }
void Insert(Node *);
void Display();
private:
int itsVal;
Node * itsNext;
};
unsigned short SomeArray[5][4];
for (int i = 0; i<4; i++)
for (int j = 0; j<5; j++)
SomeArray[i][j] = i+j;
unsigned short SomeArray[5][4];
for (int i = 0; i<=5; i++)
for (int j = 0; j<=4; j++)
SomeArray[i][j] = 0;
Base::FunctionName();
FunctionName();
virtual void SomeFunction(int);
class Square : public Rectangle
{};
Square::Square(int length):
Rectangle(length, length){}
class Square
{
public:
// ...
virtual Square * clone() const { return new Square(*this); }
// ...
};
void SomeFunction (Shape); Shape * pRect = new Rectangle; SomeFunction(*pRect);
class Shape()
{
public:
Shape();
virtual ~Shape();
virtual Shape(const Shape&);
};
class Vehicle
{
virtual void Move() = 0;
}
class JetPlane : public Rocket, public Airplane
class 747 : public JetPlane
class Vehicle
{
virtual void Move() = 0;
virtual void Haul() = 0;
};
class Car : public Vehicle
{
virtual void Move();
virtual void Haul();
};
class Bus : public Vehicle
{
virtual void Move();
virtual void Haul();
};
class Vehicle
{
virtual void Move() = 0;
virtual void Haul() = 0;
};
class Car : public Vehicle
{
virtual void Move();
};
class Bus : public Vehicle
{
virtual void Move();
virtual void Haul();
};
class SportsCar : public Car
{
virtual void Haul();
};
class Coupe : public Car
{
virtual void Haul();
};
static int itsStatic;
static int SomeFunction();
long (* function)(int);
long ( Car::*function)(int);
(long ( Car::*function)(int) theArray [10];
1: class myClass
2: {
3: public:
4: myClass();
5: ~myClass();
6: private:
7: int itsMember;
8: static int itsStatic;
9: };
10:
11: myClass::myClass():
12: itsMember(1)
13: {
14: itsStatic++;
15: }
16:
17: myClass::~myClass()
18: {
19: itsStatic--;
20: }
21:
22: int myClass::itsStatic = 0;
23:
24: int main()
25: {}
1: #include <iostream.h>
2:
3: class myClass
4: {
5: public:
6: myClass();
7: ~myClass();
8: void ShowMember();
9: void ShowStatic();
10: private:
11: int itsMember;
12: static int itsStatic;
13: };
14:
15: myClass::myClass():
16: itsMember(1)
17: {
18: itsStatic++;
19: }
20:
21: myClass::~myClass()
22: {
23: itsStatic--;
24: cout << "In destructor. ItsStatic: " << itsStatic << endl;
25: }
26:
27: void myClass::ShowMember()
28: {
29: cout << "itsMember: " << itsMember << endl;
30: }
31:
32: void myClass::ShowStatic()
33: {
34: cout << "itsStatic: " << itsStatic << endl;
35: }
36: int myClass::itsStatic = 0;
37:
38: int main()
39: {
40: myClass obj1;
41: obj1.ShowMember();
42: obj1.ShowStatic();
43:
44: myClass obj2;
45: obj2.ShowMember();
46: obj2.ShowStatic();
47:
48: myClass obj3;
49: obj3.ShowMember();
50: obj3.ShowStatic();
51: return 0;
52: }
1: #include <iostream.h>
2:
3: class myClass
4: {
5: public:
6: myClass();
7: ~myClass();
8: void ShowMember();
9: static int GetStatic();
10: private:
11: int itsMember;
12: static int itsStatic;
13: };
14:
15: myClass::myClass():
16: itsMember(1)
17: {
18: itsStatic++;
19: }
20:
21: myClass::~myClass()
22: {
23: itsStatic--;
24: cout << "In destructor. ItsStatic: " << itsStatic << endl;
25: }
26:
27: void myClass::ShowMember()
28: {
29: cout << "itsMember: " << itsMember << endl;
30: }
31:
32: int myClass::itsStatic = 0;
33:
34: void myClass::GetStatic()
35: {
36: return itsStatic;
37: }
38:
39: int main()
40: {
41: myClass obj1;
42: obj1.ShowMember();
43: cout << "Static: " << myClass::GetStatic() << endl;
44:
45: myClass obj2;
46: obj2.ShowMember();
47: cout << "Static: " << myClass::GetStatic() << endl;
48:
49: myClass obj3;
50: obj3.ShowMember();
51: cout << "Static: " << myClass::GetStatic() << endl;
52: return 0;
53: }
1: #include <iostream.h>
2:
3: class myClass
4: {
5: public:
6: myClass();
7: ~myClass();
8: void ShowMember();
9: static int GetStatic();
10: private:
11: int itsMember;
12: static int itsStatic;
13: };
14:
15: myClass::myClass():
16: itsMember(1)
17: {
18: itsStatic++;
19: }
20:
21: myClass::~myClass()
22: {
23: itsStatic--;
24: cout << "In destructor. ItsStatic: " << itsStatic << endl;
25: }
26:
27: void myClass::ShowMember()
28: {
29: cout << "itsMember: " << itsMember << endl;
30: }
31:
32: int myClass::itsStatic = 0;
33:
34: int myClass::GetStatic()
35: {
36: return itsStatic;
37: }
38:
39: int main()
40: {
41: void (myClass::*PMF) ();
42:
43: PMF=myClass::ShowMember;
44:
45: myClass obj1;
46: (obj1.*PMF)();
47: cout << "Static: " << myClass::GetStatic() << endl;
48:
49: myClass obj2;
50: (obj2.*PMF)();
51: cout << "Static: " << myClass::GetStatic() << endl;
52:
53: myClass obj3;
54: (obj3.*PMF)();
55: cout << "Static: " << myClass::GetStatic() << endl;
56: return 0;
57: }
1: #include <iostream.h>
2:
3: class myClass
4: {
5: public:
6: myClass();
7: ~myClass();
8: void ShowMember();
9: void ShowSecond();
10: void ShowThird();
11: static int GetStatic();
12: private:
13: int itsMember;
14: int itsSecond;
15: int itsThird;
16: static int itsStatic;
17: };
18:
19: myClass::myClass():
20: itsMember(1),
21: itsSecond(2),
22: itsThird(3)
23: {
24: itsStatic++;
25: }
26:
27: myClass::~myClass()
28: {
29: itsStatic--;
30: cout << "In destructor. ItsStatic: " << itsStatic << endl;
31: }
32:
33: void myClass::ShowMember()
34: {
35: cout << "itsMember: " << itsMember << endl;
36: }
37:
38: void myClass::ShowSecond()
39: {
40: cout << "itsSecond: " << itsSecond << endl;
41: }
42:
43: void myClass::ShowThird()
44: {
45: cout << "itsThird: " << itsThird << endl;
46: }
47: int myClass::itsStatic = 0;
48:
49: int myClass::GetStatic()
50: {
51: return itsStatic;
52: }
53:
54: int main()
55: {
56: void (myClass::*PMF) ();
57:
58: myClass obj1;
59: PMF=myClass::ShowMember;
60: (obj1.*PMF)();
61: PMF=myClass::ShowSecond;
62: (obj1.*PMF)();
63: PMF=myClass::ShowThird;
64: (obj1.*PMF)();
65: cout << "Static: " << myClass::GetStatic() << endl;
66:
67: myClass obj2;
68: PMF=myClass::ShowMember;
69: (obj2.*PMF)();
70: PMF=myClass::ShowSecond;
71: (obj2.*PMF)();
72: PMF=myClass::ShowThird;
73: (obj2.*PMF)();
74: cout << "Static: " << myClass::GetStatic() << endl;
75:
76: myClass obj3;
77: PMF=myClass::ShowMember;
78: (obj3.*PMF)();
79: PMF=myClass::ShowSecond;
80: (obj3.*PMF)();
81: PMF=myClass::ShowThird;
82: (obj3.*PMF)();
83: cout << "Static: " << myClass::GetStatic() << endl;
84: return 0;
85: }
class Animal:
{
private:
String itsName;
};
class boundedArray : public Array
{
//...
}
class Set : private Array
{
// ...
}
1: #include <iostream.h>
2: #include <string.h>
3:
4: class String
5: {
6: public:
7: // constructors
8: String();
9: String(const char *const);
10: String(const String &);
11: ~String();
12:
13: // overloaded operators
14: char & operator[](int offset);
15: char operator[](int offset) const;
16: String operator+(const String&);
17: void operator+=(const String&);
18: String & operator= (const String &);
19: friend ostream& operator<<
20: ( ostream& _theStream,String& theString);
21: friend istream& operator>>
22: ( istream& _theStream,String& theString);
23: // General accessors
24: int GetLen()const { return itsLen; }
25: const char * GetString() const { return itsString; }
26: // static int ConstructorCount;
27:
28: private:
29: String (int); // private constructor
30: char * itsString;
31: unsigned short itsLen;
32:
33 };
34:
35: ostream& operator<<( ostream& theStream,String& theString)
36: {
37: theStream << theString.GetString();
38: return theStream;
39: }
40:
41: istream& operator>>( istream& theStream,String& theString)
42: {
43: theStream >> theString.GetString();
44: return theStream;
45: }
46:
47: int main()
48: {
49: String theString("Hello world.");
50: cout << theString;
51: return 0;
52: }
1: #include <iostream.h>
2:
3: class Animal;
4:
5: void setValue(Animal& , int);
6:
7:
8: class Animal
9: {
10: public:
11: int GetWeight()const { return itsWeight; }
12: int GetAge() const { return itsAge; }
13: private:
14: int itsWeight;
15: int itsAge;
16: };
17:
18: void setValue(Animal& theAnimal, int theWeight)
19: {
20: friend class Animal;
21: theAnimal.itsWeight = theWeight;
22: }
23:
24: int main()
25: {
26: Animal peppy;
27: setValue(peppy,5);
28: return 0;
29: }
1: #include <iostream.h>
2:
3: class Animal;
4:
5: void setValue(Animal& , int);
6:
7:
8: class Animal
9: {
10: public:
11: friend void setValue(Animal&, int);
12: int GetWeight()const { return itsWeight; }
13: int GetAge() const { return itsAge; }
14: private:
15: int itsWeight;
16: int itsAge;
17: };
18:
19: void setValue(Animal& theAnimal, int theWeight)
20: {
21: theAnimal.itsWeight = theWeight;
22: }
23:
24: int main()
25: {
26: Animal peppy;
27: setValue(peppy,5);
28: return 0;
29: }
1: #include <iostream.h>
2:
3: class Animal;
4:
5: void setValue(Animal& , int);
6: void setValue(Animal& ,int,int);
7:
8: class Animal
9: {
10: friend void setValue(Animal& ,int); // here's the change!
11: private:
12: int itsWeight;
13: int itsAge;
14: };
15:
16: void setValue(Animal& theAnimal, int theWeight)
17: {
18: theAnimal.itsWeight = theWeight;
19: }
20:
21:
22: void setValue(Animal& theAnimal, int theWeight, int theAge)
23: {
24: theAnimal.itsWeight = theWeight;
25: theAnimal.itsAge = theAge;
26: }
27:
28: int main()
29: {
30: Animal peppy;
31: setValue(peppy,5);
32: setValue(peppy,7,9);
33: return 0;
34: }
1: #include <iostream.h>
2:
3: class Animal;
4:
5: void setValue(Animal& , int);
6: void setValue(Animal& ,int,int); // here's the change!
7:
8: class Animal
9: {
10: friend void setValue(Animal& ,int);
11: friend void setValue(Animal& ,int,int);
12: private:
13: int itsWeight;
14: int itsAge;
15: };
16:
17: void setValue(Animal& theAnimal, int theWeight)
18: {
19: theAnimal.itsWeight = theWeight;
20: }
21:
22:
23: void setValue(Animal& theAnimal, int theWeight, int theAge)
24: {
25: theAnimal.itsWeight = theWeight;
26: theAnimal.itsAge = theAge;
27: }
28:
29: int main()
30: {
31: Animal peppy;
32: setValue(peppy,5);
33: setValue(peppy,7,9);
34: return 0;
35: }
1: #include <iostream.h>
2: int main()
3: {
4: int x;
5: cout << "Enter a number: ";
6: cin >> x;
7: cout << "You entered: " << x << endl;
8: cerr << "Uh oh, this to cerr!" << endl;
9: clog << "Uh oh, this to clog!" << endl;
10: return 0;
11: }
1: #include <iostream.h>
2: int main()
3: {
4: char name[80];
5: cout << "Enter your full name: ";
6: cin.getline(name,80);
7: cout << "\nYou entered: " << name << endl;
8: return 0;
9: }
1: // Listing
2: #include <iostream.h>
3:
4: int main()
5: {
6: char ch;
7: cout << "enter a phrase: ";
8: while ( cin.get(ch) )
9: {
10: switch (ch)
11: {
12: case `!':
13: cout << `$';
14: break;
15: case `#':
16: break;
17: default:
18: cout << ch;
19: break;
20: }
21: }
22: return 0;
23: }
1: #include <fstream.h>
2: enum BOOL { FALSE, TRUE };
3:
4: int main(int argc, char**argv) // returns 1 on error
5: {
6:
7: if (argc != 2)
8: {
9: cout << "Usage: argv[0] <infile>\n";
10: return(1);
11: }
12:
13: // open the input stream
14: ifstream fin (argv[1],ios::binary);
15: if (!fin)
16: {
17: cout << "Unable to open " << argv[1] << " for reading.\n";
18: return(1);
19: }
20:
21: char ch;
22: while ( fin.get(ch))
23: if ((ch > 32 && ch < 127) || ch == `\n' || ch == `\t')
24: cout << ch;
25: fin.close();
26: }
1: #include <fstream.h>
2:
3: int main(int argc, char**argv) // returns 1 on error
4: {
5: for (int ctr = argc; ctr ; ctr--)
6: cout << argv[ctr] << " ";
7: }
#ifndef STRING_H #define STRING_H ... #endif
1: #include <iostream.h>
2:
3: #ifndef DEBUG
4: #define ASSERT(x)
5: #elif DEBUG == 1
6: #define ASSERT(x) \
7: if (! (x)) \
8: { \
9: cout << "ERROR!! Assert " << #x << " failed\n"; \
10: }
11: #elif DEBUG == 2
12: #define ASSERT(x) \
13: if (! (x) ) \
14: { \
15: cout << "ERROR!! Assert " << #x << " failed\n"; \
16: cout << " on line " << __LINE__ << "\n"; \
17: cout << " in file " << __FILE__ << "\n"; \
18: }
19: #endif
#ifndef DEBUG #define DPRINT(string) #else #define DPRINT(STRING) cout << #STRING ; #endif
1: #include <iostream.h>
2:
3: void ErrorFunc(
4: int LineNumber,
5: const char * FileName)
6: {
7: cout << "An error occurred in file ";
8: cout << FileName;
9: cout << " at line "
10: cout << LineNumber << endl;
11: }
1: // driver program to exercise ErrorFunc
2: int main()
3: {
4: cout << "An error occurs on next line!";
5: ErrorFunc(__LINE__, __FILE__);
6: return 0;
7: }
1: #include <iostream.h>
2:
3: #define DEBUG // turn error handling on
4:
5: #ifndef DEBUG
6: #define ASSERT(x)
7: #else
8: #define ASSERT(X) \
9: if (! (X)) \
10: { \
11: ErrorFunc(__LINE__, __FILE__); \
12: }
13: #endif
14:
15: void ErrorFunc(int LineNumber, const char * FileName)
16: {
17: cout << "An error occurred in file ";
18: cout << FileName;
19: cout << " at line ";
20: cout << LineNumber << endl;
21: }
22:
23: // driver program to exercise ErrorFunc
24: int main()
25: {
26: int x = 5;
27: ASSERT(x >= 5); // no error
28: x = 3;
29: ASSERT(x >= 5); // error!
30: return 0;
31: }
1: // driver program to exercise ErrorFunc
2: int main()
3: {
4: int x = 5;
5: if (! (x >= 5)) {ErrorFunc(__LINE__, __FILE__);}
6: x = 3;
7: if (! (x >= 5)) {ErrorFunc(__LINE__, __FILE__);}
8: return 0;
9: }
class Entity; // a client of the intersection // the root of all cars, trucks, bicycles and emergency vehicles. class Vehicle : Entity ...; // the root of all People class Pedestrian : Entity...; class Car : public Vehicle...; class Truck : public Vehicle...; class Motorcycle : public Vehicle...; class Bicycle : public Vehicle...; class Emergency_Vehicle : public Vehicle...; // contains lists of cars and people waiting to pass
class Intersection;
class Local_Car : public Car...;
class Tourist_Car : public Car...;
class Taxi : public Car...;
class Local_Pedestrian : public
Pedestrian...;
class Tourist_Pedestrian : public
Pedestrian...;
class Boston_Bicycle : public Bicycle...;
class Calendar_Class; // forward reference
class Meeting; // forward reference
class Configuration
{
public:
Configuration();
~Configuration();
Meeting Schedule( ListOfPerson&, Delta Time
duration );
Meeting Schedule( ListOfPerson&, Delta Time
duration, Time );
Meeting Schedule( ListOfPerson&, Delta Time
duration, Room );
ListOfPerson& People(); // public
accessors
ListOfRoom& Rooms(); // public accessors
protected:
ListOfRoom rooms;
ListOfPerson people;
};
typedef long Room_ID;
class Room
{
public:
Room( String name, Room_ID id, int capacity,
String directions = "", String description = "" );
~Room();
Calendar_Class Calendar();
protected:
Calendar_Class calendar;
int capacity;
Room_ID id;
String name;
String directions; // where is
this room?
String description;
};
typedef long Person_ID;
class Person
{
public:
Person( String name, Person_ID id );
~Person();
Calendar_Class Calendar(); // the access
point to add meetings
protected:
Calendar_Class calendar;
Person_ID id;
String name;
};
class Calendar_Class
{
public:
Calendar_Class();
~Calendar_Class();
void Add( const Meeting& ); // add a
meeting to the calendar
void Delete( const Meeting& );
Meeting* Lookup( Time ); // see if
there is a meeting at the
// given time
Block( Time, Duration, String reason = "" );
// allocate time to yourself...
protected:
OrderedListOfMeeting meetings;
};
class Meeting
{
public:
Meeting( ListOfPerson&, Room room,
Time when, Duration duration, String purpose
= "" );
~Meeting();
protected:
ListOfPerson people;
Room room;
Time when;
Duration duration;
String purpose;
};
class List
{
private:
public:
List():head(0),tail(0),theCount(0) {}
virtual ~List();
void insert( int value );
void append( int value );
int is_present( int value ) const;
int is_empty() const { return head == 0; }
int count() const { return theCount; }
private:
class ListCell
{
public:
ListCell(int value, ListCell *cell = 0):val(value),next(cell){}
int val;
ListCell *next;
};
ListCell *head;
ListCell *tail;
int theCount;
};
Here is one way to implement this template:
template <class Type>
class List
{
public:
List():head(0),tail(0),theCount(0) { }
virtual ~List();
void insert( Type value );
void append( Type value );
int is_present( Type value ) const;
int is_empty() const { return head == 0; }
int count() const { return theCount; }
private:
class ListCell
{
public:
ListCell(Type value, ListCell *cell = 0):val(value),next(cell){}
Type val;
ListCell *next;
};
ListCell *head;
ListCell *tail;
int theCount;
};
void List::insert(int value)
{
ListCell *pt = new ListCell( value, head );
assert (pt != 0);
// this line added to handle tail
if ( head == 0 ) tail = pt;
head = pt;
theCount++;
}
void List::append( int value )
{
ListCell *pt = new ListCell( value );
if ( head == 0 )
head = pt;
else
tail->next = pt;
tail = pt;
theCount++;
}
int List::is_present( int value ) const
{
if ( head == 0 ) return 0;
if ( head->val == value || tail->val == value )
return 1;
ListCell *pt = head->next;
for (; pt != tail; pt = pt->next)
if ( pt->val == value )
return 1;
return 0;
}
template <class Type>
List<Type>::~List()
{
ListCell *pt = head;
while ( pt )
{
ListCell *tmp = pt;
pt = pt->next;
delete tmp;
}
head = tail = 0;
}
template <class Type>
void List<Type>::insert(Type value)
{
ListCell *pt = new ListCell( value, head );
assert (pt != 0);
// this line added to handle tail
if ( head == 0 ) tail = pt;
head = pt;
theCount++;
}
template <class Type>
void List<Type>::append( Type value )
{
ListCell *pt = new ListCell( value );
if ( head == 0 )
head = pt;
else
tail->next = pt;
tail = pt;
theCount++;
}
template <class Type>
int List<Type>::is_present( Type value ) const
{
if ( head == 0 ) return 0;
if ( head->val == value || tail->val == value )
return 1;
ListCell *pt = head->next;
for (; pt != tail; pt = pt->next)
if ( pt->val == value )
return 1;
return 0;
}
List<String> string_list; List<Cat> Cat_List; List<int> int_List;
List<Cat> Cat_List;
Cat Felix;
CatList.append( Felix );
cout << "Felix is " <<
( Cat_List.is_present( Felix ) ) ? "" : "not " << "present\n";
friend int operator==( const Type& lhs, const Type& rhs );
template <class Type>
int List<Type>::operator==( const Type& lhs, const Type& rhs )
{
// compare lengths first
if ( lhs.theCount != rhs.theCount )
return 0; // lengths differ
ListCell *lh = lhs.head;
ListCell *rh = rhs.head;
for(; lh != 0; lh = lh.next, rh = rh.next )
if ( lh.value != rh.value )
return 0;
return 1; // if they don't differ, they must match
}
// template swap:
// must have assignment and the copy constructor defined for the Type.
template <class Type>
void swap( Type& lhs, Type& rhs)
{
Type temp( lhs );
lhs = rhs;
rhs = temp;
}
#include <iostream.h>
class OutOfMemory {};
int main()
{
try
{
int *myInt = new int;
if (myInt == 0)
throw OutOfMemory();
}
catch (OutOfMemory)
{
cout << "Unable to allocate memory!\n";
}
return 0;
}
#include <iostream.h>
#include <stdio.h>
#include <string.h>
class OutOfMemory
{
public:
OutOfMemory(char *);
char* GetString() { return itsString; }
private:
char* itsString;
};
OutOfMemory::OutOfMemory(char * theType)
{
itsString = new char[80];
char warning[] = "Out Of Memory! Can't allocate room for: ";
strncpy(itsString,warning,60);
strncat(itsString,theType,19);
}
int main()
{
try
{
int *myInt = new int;
if (myInt == 0)
throw OutOfMemory("int");
}
catch (OutOfMemory& theException)
{
cout << theException.GetString();
}
return 0;
}
1: #include <iostream.h>
2:
3: // Abstract exception data type
4: class Exception
5: {
6: public:
7: Exception(){}
8: virtual ~Exception(){}
9: virtual void PrintError() = 0;
10: };
11:
12: // Derived class to handle memory problems.
13: // Note no allocation of memory in this class!
14: class OutOfMemory : public Exception
15: {
16: public:
17: OutOfMemory(){}
18: ~OutOfMemory(){}
19: virtual void PrintError();
20: private:
21: };
22:
23: void OutOfMemory::PrintError()
24: {
25: cout << "Out of Memory!!\n";
26: }
27:
28: // Derived class to handle bad numbers
29: class RangeError : public Exception
30: {
31: public:
32: RangeError(unsigned long number){badNumber = number;}
33: ~RangeError(){}
34: virtual void PrintError();
35: virtual unsigned long GetNumber() { return badNumber; }
36: virtual void SetNumber(unsigned long number) {badNumber = Ânumber;}
37: private:
38: unsigned long badNumber;
39: };
40:
41: void RangeError::PrintError()
42: {
43: cout << "Number out of range. You used " << GetNumber() << Â"!!\n";
44: }
45:
46: void MyFunction(); // func. prototype
47:
48: int main()
49: {
50: try
51: {
52: MyFunction();
53: }
54: // Only one catch required, use virtual functions to do the
55: // right thing.
56: catch (Exception& theException)
57: {
58: theException.PrintError();
59: }
60: return 0;
61: }
62:
63: void MyFunction()
64: {
65: unsigned int *myInt = new unsigned int;
66: long testNumber;
67: if (myInt == 0)
68: throw OutOfMemory();
69: cout << "Enter an int: ";
70: cin >> testNumber;
71: // this weird test should be replaced by a series
72: // of tests to complain about bad user input
73: if (testNumber > 3768 || testNumber < 0)
74: throw RangeError(testNumber);
75:
76: *myInt = testNumber;
77: cout << "Ok. myInt: " << *myInt;
78: delete myInt;
79: }
1: #include <iostream.h>
2:
3: // Abstract exception data type
4: class Exception
5: {
6: public:
7: Exception(){}
8: virtual ~Exception(){}
9: virtual void PrintError() = 0;
10: };
11:
12: // Derived class to handle memory problems.
13: // Note no allocation of memory in this class!
14: class OutOfMemory : public Exception
15: {
16: public:
17: OutOfMemory(){}
18: ~OutOfMemory(){}
19: virtual void PrintError();
20: private:
21: };
22:
23: void OutOfMemory::PrintError()
24: {
25: cout << "Out of Memory!!\n";
26: }
27:
28: // Derived class to handle bad numbers
29: class RangeError : public Exception
30: {
31: public:
32: RangeError(unsigned long number){badNumber = number;}
33: ~RangeError(){}
34: virtual void PrintError();
35: virtual unsigned long GetNumber() { return badNumber; }
36: virtual void SetNumber(unsigned long number) {badNumber = Ânumber;}
37: private:
38: unsigned long badNumber;
39: };
40:
41: void RangeError::PrintError()
42: {
43: cout << "Number out of range. You used " << GetNumber() << Â"!!\n";
44: }
45:
46: // func. prototypes
47: void MyFunction();
48: unsigned int * FunctionTwo();
49: void FunctionThree(unsigned int *);
50:
51: int main()
52: {
53: try
54: {
55: MyFunction();
56: }
57: // Only one catch required, use virtual functions to do the
58: // right thing.
59: catch (Exception& theException)
60: {
61: theException.PrintError();
62: }
63: return 0;
64: }
65:
66: unsigned int * FunctionTwo()
67: {
68: unsigned int *myInt = new unsigned int;
69: if (myInt == 0)
70: throw OutOfMemory();
71: return myInt;
72: }
73:
74: void MyFunction()
75: {
76: unsigned int *myInt = FunctionTwo();
77:
78: FunctionThree(myInt);
79: cout << "Ok. myInt: " << *myInt;
80: delete myInt;
81: }
82:
83: void FunctionThree(unsigned int *ptr)
84: {
85: long testNumber;
86: cout << "Enter an int: ";
87: cin >> testNumber;
88: // this weird test should be replaced by a series
89: // of tests to complain about bad user input
90: if (testNumber > 3768 || testNumber < 0)
91: throw RangeError(testNumber);
92: *ptr = testNumber;
93: }
#include "stringc.h" // our string class
class xOutOfMemory
{
public:
xOutOfMemory( const String& where ) : location( where ){}
~xOutOfMemory(){}
virtual String where(){ return location };
private:
String location;
}
main()
{
try {
char *var = new char;
if ( var == 0 )
throw xOutOfMemory();
}
catch( xOutOfMemory& theException )
{
cout << "Out of memory at " << theException.location() << "\n";
}
}
atol()
1: #include <iostream.h>
2: #include <string.h>
3:
4: int main()
5: {
6: char bigString[21] = "12345678901234567890";
7: char smallString[10];
8: strncpy(smallString,bigString,9);
9: smallString[9]='\0';
10: cout << "BigString: " << bigString << endl;
11: cout << "smallString: " << smallString << endl;
12: return 0;
13: }
1: #include <iostream.h>
2: #include <time.h>
3:
4: int main()
5: {
6: time_t currentTime;
7: struct tm *timeStruct;
8: time (¤tTime);
9: timeStruct = localtime(¤tTime);
10:
11: cout << timeStruct->tm_mon+1 << "/";
12: cout << timeStruct->tm_mday << "/";
13: cout << timeStruct->tm_year << " ";
14: return 0;
15: }
#include <iostream.h>
enum Boolean { FALSE = 0, TRUE = 1 };
class Computer
{
public: // types
enum Machine { Mac = 0, PC };
public: // methods
Computer( Boolean color, Boolean laptop, Machine kind, Boolean cdrom )
: Color( color ), Laptop( laptop ), Kind( kind ), CDRom( cdrom ){}
~Computer(){}
friend ostream& operator<<( ostream& os, const Computer& computer );
private:
Boolean Color : 1;
Boolean Laptop : 1;
Machine Kind : 1;
Boolean CDRom : 1;
};
ostream&
operator<<( ostream& os, const Computer& computer )
{
os << "[";
( computer.Color ) ? os << "color" : os << "monochrome";
os << ", ";
( computer.Laptop ) ? os << "laptop" : os << "desktop";
os << ", ";
( computer.Kind ) ? os << "PC" : os << "Mac";
os << ", ";
( computer.CDRom ) ? os << "" : os << "no ";
os << "CD-Rom";
os << "]";
return os;
}
int main()
{
Computer pc( TRUE, TRUE, Computer :: PC, TRUE );
cout << pc << `\n';
return 0;
}
#include <ctype.h>
#include <iostream.h>
#include <string.h>
class Bits
{
public:
enum { BITS_PER_INT = 16 };
Bits( int cnt );
virtual ~Bits();
void clear();
void set( int position );
void reset( int position );
int is_set( int position );
private:
unsigned int * bits;
int count;
int Ints_Needed;
};
class AlphaBits : private Bits
{
public:
AlphaBits() : Bits( 26 ){}
~AlphaBits(){}
void clear() { Bits::clear(); }
void set( char );
void reset( char );
int is_set( char );
};
Bits :: Bits( int cnt ) : count( cnt )
{
Ints_Needed = count / BITS_PER_INT;
// if there is a remainder, you need one more member in array
if ( 0 != count % BITS_PER_INT )
Ints_Needed++;
// create an array of ints to hold all the bits
bits = new unsigned int[ Ints_Needed ];
clear();
}
Bits :: ~Bits()
{
delete [] bits;
}
void Bits :: clear()
{
// clear the bits
for ( int i = 0; i < Ints_Needed; i++ )
bits[ i ] = 0;
}
void Bits :: set( int position )
{
// find the bit to set
int Int_Number = position / BITS_PER_INT;
int Bit_Number = position % BITS_PER_INT;
// create mask with that one bit set
unsigned int mask = 1 << Bit_Number;
// set the bit
bits[ Int_Number ] |= mask;
}
// clear the bit
void Bits :: reset( int position )
{
int Int_Number = position / BITS_PER_INT;
int Bit_Number = position % BITS_PER_INT;
unsigned int mask = ~( 1 << Bit_Number );
bits[ Int_Number ] &= mask;
}
int Bits :: is_set( int position )
{
int Int_Number = position / BITS_PER_INT;
int Bit_Number = position % BITS_PER_INT;
unsigned int mask = 1 << Bit_Number;
return ( 0 != ( bits[ Int_Number ] & mask ) );
}
void AlphaBits :: set( char s )
{
// make sure the requested character is an alphabetic character
// if so, force it to lower case, then subtract the ascii value
// of `a' to get its ordinal (where a = 0, b =1) and set that bit
if ( isalpha( s ) )
Bits :: set( tolower( s ) - `a' );
}
void AlphaBits :: reset( char s )
{
if ( isalpha( s ) )
Bits :: reset( tolower( s ) - `a' );
}
int AlphaBits :: is_set( char s )
{
if ( isalpha( s ) )
return Bits :: is_set( tolower( s ) - `a' );
else
return 0;
}
int main()
{
AlphaBits letters;
char buffer[512];
for (;;)
{
cout << "\nPlease type a word (0 to quit): ";
cin >> buffer;
if (strcmp(buffer,"0") == 0)
break;
// set the bits
for ( char *s = buffer; *s; s++ )
letters.set( *s );
// print the results
cout << "The letters used were: ";
for ( char c = `a'; c <= `z'; c++ )
if ( letters.is_set( c ) )
cout << c << ` `;
cout << `\n';
// clear the bits
letters.clear();
}
return 0;
#include <string.h>
#include <iostream.h>
void swap ( char* &s, char* &t )
{
char* temp = s;
s = t;
t = temp;
}
int main( int argc, char* argv[] )
{
// Since argv[0] is the program name,
//we don't want to sort or print it;
// we start sorting at element 1 (not 0).
// a "Bubble Sort" is used because of the small number of items.
int i,j;
for ( i = 1; i < argc; i++ )
for ( j = i + 1; j < argc; j++ )
if ( 0 < strcmp( argv[i], argv[j] ) )
swap( argv[i], argv[j] );
for ( i = 1; i < argc; i++ )
cout << argv[i] << ` `;
cout << `\n';
return 0;
}
101 // 5 001 //1 110 //6
lhs rhs | carry result ------------+------------------ 0 0 | 0 0 0 1 | 0 1 1 0 | 0 1 1 1 | 1 0
#include <iostream.h>
unsigned int add( unsigned int lhs, unsigned int rhs )
{
unsigned int result, carry;
while ( 1 )
{
result = lhs ^ rhs;
carry = lhs & rhs;
if ( carry == 0 )
break;
lhs = carry << 1;
rhs = result;
};
return result;
}
int main()
{
unsigned long a, b;
for (;;)
{
cout << "Enter two numbers. (0 0 to stop): ";
cin >> a >> b;
if (!a && !b)
break;
cout <<a << " + " << b << " = " << add(a,b) << endl;
}
return 0;
}
#include <iostream.h>
unsigned int add( unsigned int lhs, unsigned int rhs )
{
unsigned int carry = lhs & rhs;
unsigned int result = lhs ^ rhs;
if ( carry )
return add( result, carry << 1 );
else
return result;
}
int main()
{
unsigned long a, b;
for (;;)
{
cout << "Enter two numbers. (0 0 to stop): ";
cin >> a >> b;
if (!a && !b)
break;
cout <<a << " + " << b << " = " << add(a,b) << endl;
}
return 0;
}