The main Function
Below you'll find the code for the f2c
program. Use the arrow on the left to show and hide the code as we
discuss its various features.
The f2c Source Code
/**
* @file f2c.cpp
* @author Stephen Gilbert
* @version CS 150 Reader
* Converts Fahrenheit to Celsius.
*/
#include <iostream>
#include <iomanip>
using namespace std;
double convert(double temp);
int main()
{
cout << "Enter a temperature in Fahrenheit: ";
double fahr;
cin >> fahr;
double celsius = convert(fahr);
cout << "Converted: " << fahr << "F -> "
<< celsius << "C" << endl;
return 0;
}
/**
* Converts a temperature from Fahrenheit to Celsius.
* @param temp the Fahrenheit temperature to convert.
* @return the Celsius temperature.
*/
double convert(double temp)
{
return (temp - 32) * 5.0 / 9.0;
}
A function is a named section of code
that performs an operation. Every C++ program must contain
exactly one function with the name main,
which is automatically called when your program starts up.
- Each statement in the body of the
main function is then run
(or executed), one after another,
in order. This concept is called
sequence.
- When main has finished its work, execution
of the program ends.
The main function contains six different statements.
- Line 15 is an output statement. It prints a
prompt, telling the user what to enter. cout
is the standard output stream (similar to System.out
in Java or stdout in Python). The characters in quotes
(generically called a string literal) are sent to
the screen using the insertion operator (<<).
- Line 16 is a variable definition for fahr,
a floating-point number, called double in C++,
which is uninitialized.
- Line 17 is an input statement. cin is
similar to a Scanner object in Java, or a file
object in Python. It reads a sequence of characters from the keyboard
and stores the converted value in fahr using the
>> (or extraction) operator.
- Line 18 has both a variable definition and a
function call. The line calls the function
named convert, passing a copy of
fahr as an argument. Then, it defines a
variable, celsius, and initializes
it with the returned value.
- Lines 19 and 20 are a single output statement, spread
over two lines. The statement combines text and variables to produce the
desired result.
- Line 21 is a return statement which ends the program
and returns a value to the operating system. 0 indicates
success, while anything else signals failure. You may omit
this return statement in main, but not
in any other function.