Sample Programs Tuesday 7/9/02 Program #1 ---------- // My first program :) // Author : Me // Date: 7/9/02 #include int main() { cout << "My Comp. Sci. teacher is my favorite teacher!!!" << endl; return 0; } Program #2 ---------- // My second program :) // Author : Me, what a surprise // Date: 7/9/02 int main() { double inches, centimeters; cout << "Enter your height is inches : " << flush; cin >> inches; centimeters = 2.54*inches; cout << "You are " << centimeters << " cm tall." << endl; } Program #3 ---------- // My third program :) // Author : Me, I am on a roll!!! // Date: 7/9/02 int main() { char sex; int age; double weight; // Read in necessary info here cout << "Enter your sex(M/F) : " << flush; cin >> sex; cout << "How old are you? : " << flush; cin >> age; cout << "How much do you weigh? : " << flush; cin >> weight; // Print out profile cout << "Here is your profile : " << endl; cout << "Sex : " << sex << endl; cout << "Age : " << age << endl; cout << "Weight : " << weight << endl; } Program #4 ---------- // This test program illustrates the use of assignment statements and // basic arithmetic operations. int main() { int a=1, b, c=0; b = 17 + c; c = a + b*c; b = b % 7; a = (15 + a)/5; cout << a << " is a.\n"; cout << b << " is b.\n"; cout << c << " is c.\n"; } Example #5 ---------- // This program illustrates how to cast the type of a value. #include int main() { int hits, atbats; double average; cout << "Enter number of hits for the year : " << flush; cin >> hits; cout << "Enter number of at bats for the year : " << flush; cin >> atbats; average = hits/atbats; cout << "You would think your average is " << average << endl; average = (double)hits/atbats; cout << "but it is really " << average << endl; return 0; } Output ------ Enter number of hits for the year : 200 Enter number of at bats for the year : 499 You would think your average is 0 but it is really 0.400802 Example #6 ---------- // This program illustrates another work around to example 5. #include int main() { int hits; double atbats, average; cout << "Enter number of hits for the year : " << flush; cin >> hits; cout << "Enter number of at bats for the year : " << flush; cin >> atbats; average = hits/atbats; cout << "Your average is " << average << endl; return 0; } Output ------ Enter number of hits for the year : 300 Enter number of at bats for the year : 650 Your average is 0.461538 Example #7 ---------- // This example illustrates the use of constants in a program. #include int main() { const double pi = 3.14159265358979; double radius; cout << "Enter the radius of your planet : " << flush; cin >> radius; cout << "The approximate surface area of your planet is " << 4*pi*radius*radius << endl; return 0; } Output ------ Enter the radius of your planet : 23.6 The approximate surface area of your planet is 6998.97