Setting out to C++ |
|---|
// myfirst.cpp--displays a message
#include <iostream.h> // a PREPROCESSOR directive
int main(void) // heading summarizes
// function
{ // start of function body
cout << "Come up and C++ me some time."; // message
cout << "\n"; // start a new line
return 0; // terminate main()
} // end of function body
// fleas.cpp -- display the value of a variable
#include <iostream.h>
int main(void)
{
int fleas; // create an integer variable
fleas = 28; // give a value to the variable
cout << "My cat has ";
cout << fleas; // display the value of fleas
cout << " fleas.\n";
return 0;
}
// yourcat.cpp -- input and output
#include <iostream.h>
#include <stdio.h> // used for old C I/O functions
int main(void)
{
int fleas;
puts("How many fleas does your cat have?"); // Old C
cin >> fleas; // C++ input
// next line concatenates output
cout << "Well, that's " << fleas << " fleas too many.\n";
return 0;
}
// sqrt.cpp -- use a square root function
#include <iostream.h>
#include <math.h> // use with math functions
int main(void)
{
double cover; // use double for real numbers
cout << "How many square feet of sheets do you have?\n";
cin >> cover;
double side; // create another variable
side = sqrt(cover); // call function, assign return value
cout << "You can cover a square with sides of " << side;
cout << " feet\nwith your sheets.\n";
return 0;
}
// ourfunc.cpp -- defining your own function
#include <iostream.h>
void simon(int); // function prototype for simon()
int main(void)
{
simon(3); // call the simon() function
cout << "Pick an integer: ";
int count;
cin >> count;
simon(count); // call it again
return 0;
}
void simon(int n) // define the simon() function
{
cout << "Simon says touch your toes " << n << " times.\n";
}
// void functions don't need return
// convert.cpp -- converts stone to pounds
#include <iostream.h>
int stonetolb(int); // function prototype
int main(void)
{
int stone;
cout << "Enter the weight in stone: ";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << " stone are ";
cout << pounds << " pounds.\n";
return 0;
}
int stonetolb(int sts)
{
return 14 * sts;
}