1.3. C++ First Example

[ 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>                         1
int main() {                                2
    using namespace std;                    3
    // Declarations of variables
    int factArg = 0 ;                       4
    int fact(1) ;                           5
    do {                                    6
        cout << "Factorial of: ";           7
        cin >> factArg;                     8
        if ( factArg < 0 ) {
            cout << "No negative values, please!" << endl;
        }                                   9
    } while (factArg < 0) ;                 10
    int i = 2;
    while ( i <= factArg ) {                11
        fact = fact * i;
        i = i + 1;
    }                                       12
    cout << "The Factorial of " << factArg << " is: " << fact << endl;
    return 0;                               13
}                                           14

1

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.

2

Start of function "main" which returns an int

3

Permits us to use the symbols cin, cout, and endl without prefixing each name with std::

4

C style initialization syntax

5

C++ style initialization syntax

6

Start of "do..while" loop

7

Write to standard output

8

Read from standard input and convert to int

9

End of if block

10

if false, break out of do loop

11

Start of while loop

12

End of while block

13

When main returns 0, that normally means "no errors"

14

End of main block


src/early-examples/example0> g++ -Wall fac.cpp
src/early-examples/example0> g++ -Wall -o execFile fac.cpp
  
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>