Return to the C++ Demos Home Page

SAMS Teach Yourself C++ in 21 Days

Chapter Four

Prog 1 : Simple Prog to show old casting and the ANSI approved style.

// chap 4 STYC++ in 21
// casting

#include <iostream.h>

void intDiv(int x, int y)
{
	int z = x / y;
	cout << " z: " << z  << endl;
}

void floatDiv(int x, int y )
{
	float a = (float)x;		// old style
	float b = static_cast<float>(y);   // new preferred style
	float c = a/b;
	cout << " c: " << c  << endl;
}

int main()
{
	int x = 5, y = 3;
	intDiv(x,y);
	floatDiv(x,y);
	return 1;
}

Prog 2 : Simple Branching.  I'm a Mets fan.

// chap 4 STYC++ in 21
// prog for branching based on relational operators

#include <iostream.h>

int main()
{

   int redsox, yanks, x=1;
   
   while (x)
   {
   cout << "Enter the score for the red sox: ";
   cin >> redsox;

   cout << "Now enter the yankee score : ";
   cin >> yanks;

   cout << "\n";

   if (redsox > yanks ) cout << "Go Sox!!\n";
   if (redsox < yanks ) cout << "Yankees Suck!!\n";
   if (redsox == yanks) cout << "A tie?!?!...Sugar.\n";

   cin >> x;
   }

   return 0;

}

Prog 3 : Ternary ? Op

// Sams TYC++ in 21
// chap 4 program.....
// demonstration of the conditional ternary operator ?
//

#include <iostream.h>

int main()
{
  int x,y,z;

    cout << "Enter two numbers\n" << "Num 1 : ";
	cin >> x;
	cout << "Num 2 : ";
	cin >> y;
	cout << endl;


// without the ternary

	if (x>y)
	    z = x;
		else
		z = y;

		cout << "z : " << z << endl;

// with the ternary

   z = (x>y) ? x : y;

   cout << "z : " << z << endl;

// That's all folks!!

return 0;
}

Return to the C++ Demos Home Page