Return to the C++ Demos Home Page
SAMS Teach Yourself C++ in 21 Days
Chapter Five
Prog 1 : Intro to Functions
// demonstrates function prototypes
// STYC++ in 21
//
#include <iostream.h>
int Area( int length, int width );
int main()
{
int myLength;
int myWidth;
int myArea;
cout << "Punch in your Length : ";
cin >> myLength;
cout << "Punch in your Width : ";
cin >> myWidth;
myArea = Area(myLength, myWidth);
cout << "My Area is : " << myArea << endl;
return 1;
}
int Area( int theLength, int theWidth)
{
return theLength*theWidth;
}
// end of code
Prog 2 : Local vs Global Params
// STYC++ in 21 days...chap 5
// demonstrates local vals and params
#include <iostream.h>
float Convert(float);
int main()
{
float TempFer;
float TempCel;
while(TempFer != 99) // the book didn't do while loops yet..cheatin
{
cout << "Please enter the temperature in Farenheit: ";
cin >> TempFer;
TempCel = Convert(TempFer);
cout << "Here's the temp in Celcius: " << TempCel << endl;
}
return 1;
}
float Convert( float temp)
{
float cel;
cel = ((temp - 32 ) * 5) / 9;
return cel;
}
Prog 3 : Simple Recursion for Fibinacci
// STYC++ in 21 chap 5
// demonstrates recursion.....
// fibinacci sequence
//
//
#include <iostream.h>
int fib(int n);
int main()
{
int n, answer;
cout << "Enter a number to find : ";
cin >> n;
cout << "\n\n";
answer = fib(n);
cout << answer << " is the " << n << " fibinacci number\n";
return 1;
} // end of main
int fib(int n)
{
cout << "Processing Fib(" << n << ")...";
if (n<3)
{
cout << "Return 1!\n";
return 1;
}
else
{
cout << "Call fib(" << n-2 << ") and fib(" << n-1 << "). \n";
return ( fib(n-2) + fib(n-1) );
}
}
// end of source