[ fromfile: cppintro.xml id: example1 ]
Example 1.1. src/early-examples/example0/fac.cpp
/* Computes and prints n! for a given n. Uses several basic elements of C++. */ #include <iostream> int main() { using namespace std; // Declarations of variables int factArg = 0 ; int fact(1) ; do { cout << "Factorial of: "; cin >> factArg; if ( factArg < 0 ) { cout << "No negative values, please!" << endl; } } while (factArg < 0) ; int i = 2; while ( i <= factArg ) { fact = fact * i; i = i + 1; } cout << "The Factorial of " << factArg << " is: " << fact << endl; return 0; }
Standard C++ library - In older versions of C++, you might find <iostream.h> instead, but that version is regarded as "deprecated"; i.e. its use is discouraged. | |
Start of function "main" which returns an int | |
Permits us to use the symbols cin, cout, and endl without prefixing each name with std:: | |
C style initialization syntax | |
C++ style initialization syntax | |
Start of "do..while" loop | |
Write to standard output | |
Read from standard input and convert to int | |
End of if block | |
if false, break out of do loop | |
Start of while loop | |
End of while block | |
When main returns 0, that normally means "no errors" | |
End of main block |
src/early-examples/example0> g++ -Wall fac.cpp src/early-examples/example0> g++ -Wall -o execFile fac.cpp
-Wall
enables all possible warnings about constructions that might be considered questionable even if they conform to the standard.
On a *nix system you can view the manual page, a summary of command options and how they are used, by typing the command
man g++ or info g++
For more complete gcc
documentation, visit the GNU online document center.
src/early-examples/example0> ./a.out Factorial of: -3 No negative values, please! Factorial of: 5 The Factorial of 5 is: 120 src/early-examples/example0>
A namespace (Section 20.4) is a collection of classes, functions, and objects that can be addressed with a named prefix.
The using declaration tells the compiler to add all symbols from the specified namespace (std
) into the global namespace.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |