Basic C++

In this section, we will review the programming language C++ and also provide some more detailed examples of the ideas from the previous section.

C++ is an object-oriented programming language. It has a powerful set of built-in data types and control constructs. Since C++ is a compiled language, all the code written in this language, when run, are translated to machine code by a program called the compiler.

The following is an example of C++ code that writes to the console:

//Outputs strings to command line.
#include <iostream>

using namespace std;

int main() {
    cout << "Welcome to Problem Solving with" << endl;
    cout << "Algorithms and Data Structures!" << endl;

    return 0;
}

Things to Note

Every C++ program should contain a global function called main that starts the program. When you compile a C++ program and run it, it will always start execution in the main method.

In C++ every open curly brace { must have a matched close curly brace }. These are used to start and end class, function, and method definitions.

Commands, or lines of code in C++ must end with a semicolon ;. You use the semicolon to show the end of a C++ statement, just the way you would use a period . in an English sentence.

You may wonder what #include <iostream> is used for. Any line that starts with a # is called a preprocessor directive. These lines typically appear at the top of programs.

The preprocessor reads your program before it is compiled and only executes the lines beginning with a # symbol. Think of the preprocessor as a program that “sets up” your source code for the compiler. The #include directive causes the preprocessor to include the contents of another file in the program. The word inside the brackets, iostream, is the name of the file that is to be included.

The iostream file contains code that allows a C++ program to display output on the screen and read input from the keyboard. Because this program uses cout to display screen output, the iostream file must be included. The contents of the iostream file are included in the program at the point the #include statement appears. The iostream file is called a header file, so it should be included at the head, or top, of the program.

cout allows us to send data to the console to be printed as text, cout stands for "character output". In the examples seen previously we used cout along with the insertion operator (<<) to send the text to the console to be printed.

To print more than one thing on the same line, the insertion operator (<<) can be used multiple times in a single statement to concatenate (link together) multiple pieces of output. For example:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello" << " world!";
    cout << "My name is Alex.";
    return 0;
}

In the example above you will notice that the two lines were printed on the same line. endl prints a newline character to the console (causing the cursor to go to the start of the next line). In this context, endl stands for “end line”.

endl vs \n

Using endl can be a bit inefficient, as it actually does two jobs: it moves the cursor to the next line, and it "flushes" the output (makes sure that it shows up on the screen immediately). When writing text to the console using cout, cout usually flushes output anyway (and if it doesn't, it usually doesn't matter), so having endl flush is rarely important.

Because of this, use of the \n character is typically preferred instead. The \n character moves the cursor to the next line, but doesn't do the redundant flush, so it performs better. The \n character also tends to be easier to read since it's both shorter and can be embedded into existing text.

Input Commands

cin is another predefined variable that is defined in the iostream library. Whereas cout prints data to the console using the insertion operator (<<), std::cin (which stands for "character input") reads input from keyboard using the extraction operator (>>). The input must be stored in a variable to be used.

#include <iostream>

using namespace std;

int main()
{
    std::cout << "Enter a number: "; // ask user for a number

    int x = 0; // define variable x to hold user input (and initialize it to 0)
    cin >> x;  // get number from keyboard and store it in variable x

    cout << "You entered " << x << '\n';
    return 0;
}

Try compiling this program and running it for yourself. When you run the program, line 7 will print “Enter a number: “. When the code gets to line 10, your program will wait for you to enter input. Once you enter a number (and press enter), the number you enter will be assigned to variable x. Finally, on line 12, the program will print "You entered " followed by the number you just entered.

This is an easy way to get keyboard input from the user, and we will use it in many of our examples going forward. Note that you don't need to use \n when accepting input, as the user will need to press the enter key to have their input accepted, and this will move the cursor to the next line.

Just like it is possible to output more than one bit of text in a single line, it is also possible to input more than one value on a single line:

#include <iostream>

using namespace std;

int main()
{
    std::cout << "Enter two numbers separated by a space: ";

    int x = 0; // define variable x to hold user input (and initialize it to 0)
    int y = 0; // define variable y to hold user input (and initialize it to 0)
    cin >> x >> y; // get two numbers and store in variable x and y respectively

    cout << "You entered " << x << " and " << y << '\n';

    return 0;
}

Namespaces

using namespace std;

Programs usually contain several items with unique names. Variables, functions, and objects are examples of program entities that must have names. C++ uses namespaces to organize the names of program entities.

The statement using namespace std; declares that the program will be accessing entities whose names are part of the namespace called std.

The reason the program needs access to the std namespace is because every name created by the iostream file is part of that namespace.

If you remove the namespace declaration, you would have to specify the namespace of the method, for example:

#include <iostream>

int main()
{
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

This can get pretty annoying quite quickly.

Comments

In C++ and many text-based coding languages, // is used to mark the beginning of a comment. For multi-line comments, use /* to start the comment and */ to end the comment. The compiler will skip over comments. However, it is a good idea to use comments to make notes to yourself and other programmers working with you.

Here are some examples of good commenting:

/*
    C++ Haiku
    Programmer: Justin Chung
    Date:
*/

int max = 10; // this keeps track of the max score

Knowledge Check

  1. What does iostream stand for?
  2. When does the proprocessor for a program run?
  3. What is the purpose of endl at the end of the cout statement?
  4. Write a C++ program what will print a Haiku about computer science.