Main Page | See live article | Alphabetical index

C plus plus examples

These are some examples of code from the C++ Programming Language.

Conditionals

if (tester == true) {

    cout << "true" << endl;
} else if (tester == false) {
    cout << "false" << endl;
}

This code checks whether the boolean variable is true or false and prints out the corresponding value. Note that it is the same as the following code: (If tester is not a boolean variable, and not either 0 or 1, then the code above and code below mean something completely different.)

if (tester == true) {

    cout << "true" << endl;
} else {
    cout << "false" << endl;
}

This is a more conventional way of doing it:

if(tester) {
  cout<<"true"<
You can also combine ifs, else ifs, and elses all in the same statement, such as this code that prints out a grade letter based on percentages:

if (grade >= 100) {

    cout << "A" << endl;
} else if (grade >= 80) {
    cout << "B" << endl;
} else if (grade >= 70) {
    cout << "C" << endl;
} else if (grade >= 60) {
    cout << "D" << endl;
} else {
    cout << "F" << endl;
}