1 Quick Review of Basic C++
1 Quick Review of Basic C++
• Variable names
• Loops
2 Functions
• Useful analysis/computational units.
– cout.setf()
– ShowHeader()
– sin()
return type
void, basic data types (int, double, etc.), or user/system defined types.
name
Any valid name.
<args>
The names and types of all arguments (zero or more), separated by commas.
function body
Zero or more valid statements.
• Examples:
– return 1;
– return ’A’;
– return; // optional
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
int main()
{
for( int i = 1 ; i <= 5 ; i++ )
{
cout << setw(6) << i ;
cout << setw(6) << i*i;
cout << setw(6) << i*i*i << endl;
}
return 0;
}
Output:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
Functions—Part I 5
2.6.2 Powers2.cpp
// Powers2.cpp
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
// Prototype
void ShowPowers();
int main()
{
ShowPowers();
return 0;
}
/* ShowPowers()
*
* Show the square and cube of 1 through 5.
*/
void ShowPowers()
{
for( int i = 1 ; i <= 5 ; i++ )
{
cout << setw(6) << i ;
cout << setw(6) << i*i;
cout << setw(6) << i*i*i << endl;
}
}
Functions—Part I 6
2.6.3 Powers3.cpp
// Powers3.cpp
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
// Prototypes
void ShowPowers();
int Square( int );
int Cube( int i );
int main()
{
ShowPowers();
return 0;
}
/* ShowPowers()
*
* Show the square and cube of 1 through 5.
*/
void ShowPowers()
{
for( int i = 1 ; i <= 5 ; i++ )
{
cout << setw(6) << i ;
cout << setw(6) << Square( i );
cout << setw(6) << Cube( i ) << endl;
}
}
Functions—Part I 7
/* Square()
*
* Calculate the square of an integer.
*/
/* Cube()
*
* Calculate the cube of an integer.
*/
int Cube( int i )
{
return i * i * i;
}
Functions—Part I 8
2.6.4 Powers4.cpp
// Powers4.cpp
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
// Prototypes
void ShowPowers();
double Power( double x, int pow );
int main()
{
ShowPowers();
return 0;
}
/* ShowPowers()
*
* Show the square and cube of 1 through 5.
*/
void ShowPowers()
{
for( double x = 1.0 ; x <= 5.0 ; x += 1.0 )
{
cout << setw(6) << x ;
cout << setw(6) << Power(x,2); // spaces
cout << setw(6) << Power( x, 3 ) << endl;
}
}
Functions—Part I 9
/* Power
*
* Calculate the square of an integer.
* Should check that iPow > 0!
*/
return retVal;
}
Functions—Part I 10
#include <iostream.h>
#include <fstream.h>
// prototype
double Average( double x1, double x2, double x3 );
main()
{
ofstream fOut( "Average.out", ios::out );
if( !fOut ) // verify file was opened
{
cerr << "Unable to open output file: Average.out" << endl;
exit( -1 );
}
double avg;
double x1 = 2.0;
double x2 = 3.0;
double x3 = 4.0;
fOut.close();
}
Functions—Part I 11
/* Average()
*
* Calculate the average of three real numbers.
*/
return rVal;
}
Functions—Part I 12
return iVal;
}